Tải bản đầy đủ - 0 (trang)
Chapter 19. Profiling Java Applications in Eclipse

Chapter 19. Profiling Java Applications in Eclipse

Tải bản đầy đủ - 0trang

domains,needtoberunasstandaloneapplications.Youstart

themupwhenyoudetectamemoryleakorperformanceissue

inyourapplicationandrunthemagainstyourapplication.

However,whenyouarewritingordebugginganapplication,

thereisalottobesaidforbeingabletorunaprofilerdirectly

fromwithinyourdevelopmentenvironment.Thisenablesyouto

integrateperformancetestingandprofilingdirectlyintoyour

day-to-daydevelopmentenvironmentusingthetoolwithwhich

youarefamiliar.InEclipse,youcandojustthiswiththeEclipse

Test&PerformanceToolsPlatform,orTPTP.



Chapter19.ProfilingJavaApplicationsin

Eclipse

ProfilingApplicationsfromWithinanIDE

TheEclipseTest&PerformanceToolsPlatform

InstallingTPTP

TPTPandJava6

BasicProfilingwithTPTP

StudyingMemoryUsewiththeBasicMemoryAnalysisResults

AnalyzingExecutionTime

DisplayingCoverageStatistics

UsingFilterstoRefineYourResults

ProfilingaWebApplication

Conclusion



19.1.ProfilingApplicationsfromWithin

anIDE

Recentyearshaveseenanincreasingawarenessofthe

importanceofdevelopmentbestpracticessuchasunittesting

andtest-drivendevelopment.However,unittestsarenotall

thereistotesting.High-qualitysoftwareneedstoperformwell

understress,usingsystemresourcessuchasmemoryand

processortimeefficiently.Performancebottlenecksmayneedto

beidentifiedandremovedandmemoryleaksdetectedand

eliminated.Profilingandperformancetestingplayacrucialpart

inthissideofapplicationdevelopment.Andsoftwareprofilingis

anareainwhichitisvirtuallyimpossibletoworkeffectively

withoutagoodtoolset.

Mostprofilingtools,bothintheopensourceandcommercial



domains,needtoberunasstandaloneapplications.Youstart

themupwhenyoudetectamemoryleakorperformanceissue

inyourapplicationandrunthemagainstyourapplication.

However,whenyouarewritingordebugginganapplication,

thereisalottobesaidforbeingabletorunaprofilerdirectly

fromwithinyourdevelopmentenvironment.Thisenablesyouto

integrateperformancetestingandprofilingdirectlyintoyour

day-to-daydevelopmentenvironmentusingthetoolwithwhich

youarefamiliar.InEclipse,youcandojustthiswiththeEclipse

Test&PerformanceToolsPlatform,orTPTP.



19.2.TheEclipseTest&Performance

ToolsPlatform

TheEclipseIDEproposesarichsetofoptionalplug-ins

designedtoprovideacoherent,integratedpaletteofextensions

fortheEclipsedevelopmentenvironment.Thisincludesthe

convenient,althoughoptional,profilingtoolTPTP.TPTPprovides

acomprehensivesuiteofopensourceperformancetestingand

profilingtools,includingintegratedapplicationmonitoring,

testing,tracing,andprofilingfunctionalities,aswellasstatic

codeanalysistools.AndintheEclipsetradition,TPTPismore

thansimplyasetofplug-ins;itisaplatformthatcanbeused

towritetestandperformancetoolsintegratedintotheEclipse

developmentenvironment.

TheTest&PerformanceToolsPlatformcontainsanextensive

setofprofilingtoolsforJavaapplications.Itisactually

composedoffourdistinctbutrelatedcomponents:

TheTPTPprovidesasharedunderlyinginfrastructureon

whichtheothertestingtoolsarebuilt.

Themonitoringtoolsletyoucollectdataandprovide

statisticsabouttheapplication'sruntimebehavior,both

fromapplicationlogfilesandfromtheJVMitself.

Thetestingtoolsprovideaframeworkforexecutingyour

tests,includingsupportforJUnitandwebapplication

testing.

Thetracingandprofilingtoolsallowyoutocollectand

analyzeperformance-relateddata,suchasCPUand

memoryuse.

Profilinganapplicationtypicallyinvolvesobservinghowthe

applicationcopesunderstress.Acommonwayofdoingthisis

torunasetofloadtestsonadeployedapplicationanduse

profilingtoolstorecordtheapplication'sbehavior.Youcanthen



studytheresultstoinvestigateanyperformanceissues.Thisis

oftendoneattheendoftheproject,oncetheapplicationis

almostreadyforproduction.

TPTPiswellsuitedtothistypeoftask.Atypicalusecasewould

betorunloadtestsusingaload-testingtoolsuchasJMeter

(seeChapter16),andrecordandanalyzetheperformance

statisticsusingtheTPTPtools.

However,thisisnottheonlywayyoucanprofileanapplication

withTPTP.Asarule,theearlieryoutest,thelessproblemsyou

havelateron.WithTPTP,youcanprofileyourcodeinawide

rangeofcontexts,includingJUnittestcases,Javaapplications,

andwebapplications.AnditiswellintegratedintotheEclipse

IDE.,sothereisnoreasonnottostartpreliminaryperformance

testsandprofilingearlyon.

TPTPletsyoutestseveralaspectsofyourapplication'sbehavior,

includingmemoryusage(howmanyobjectsarebeingcreated,

andhowbigtheyare),executionstatistics(wheredidthe

applicationspendthemostofit'stime),andtestcoverage(how

muchofthecodewasactuallyexecutedduringthetests).Each

ofthesecanprovideinvaluableinformationaboutyour

application'sperformance.

Thesortoftestingwearetalkingabouthereisnotoptimization

assuch.Optimizationinvolvesfine-tuningapplication

performanceusingtechniquessuchascaching.Itisahighly

technicalactivity,anditisbestdoneattheveryendofthe

project.

Thistypeofpreliminaryperformancetestingandprofiling

discussedheresimplyinvolvesmakingsurethattheapplication

performscorrectlyfromthestart,andthattherearenocoding

errorsorpoorcodingpracticesthatwillpenalizeperformance

lateron.Indeed,fixingmemoryleaksandavoidingunnecessary

objectcreationisnotoptimization:itisdebuggingand,assuch,

shouldbedoneasearlyaspossible.



Inthischapter,wewilllookathowyoucanuseTPTPto

guaranteehigh-qualityandhigh-performancecode,evenduring

unitandintegrationtesting.



19.3.InstallingTPTP

TheeasiestwaytoinstallTPTPonanexistingEclipse

installationistousetheRemoteUpdatesite(seeFigure19-1).

OpentheRemoteUpdatewindow(Help SoftwareUpdates

FindandInstall),andselecttheDiscoverySiteforyourversion

ofEclipse.FortheEuropaedition,forexample,thisiscalledthe

"EuropaDiscoverySite."Here,Eclipsewillproposethesetof

plug-ins.TheTPTPtoolsarelistedunder"Testingand

Performance."Theeasiestoption,albeitthemosttimeconsuming,isjusttoinstallalltheproposedplug-ins.Evenif

youdon'tinstalltheentiretoolset,youwillstillneedtoinstall

someothercomponentsneededbyTPTP,suchas"Chartingand

Reporting,""EnablingFeatures,"and"DataToolPerformance."

Figure19-1.InstallingTPTPfromtheEuropaDiscovery

remotesite



19.4.TPTPandJava6

AnimportantthingtoknowaboutTPTPisthat,atthetimeof

thiswriting(usingEclipse3.3Europa),theTPTPprofilingtools

donotsupportJava6.TPTPreliesonJVMPI(JVMprofiling

interface),whichitusestocapturedataaboutapplications

runningintheJVM.NowJVMPIwasdroppedinJava6infavor

ofthemoremodernandflexibleJVMTI(JVMToolInterface).If

youtrytorunTPTPusingaJava6VM,youwillobtainanerror

alongthelinesof"FATALERROR:JVMPI,anexperimental

interface,isnolongersupported."SoifyouareusingJava6,

makesurethatyouarerunningEclipseunderJava5ifyou

wanttouseTPTP.

YoucanrunEclipseusingadifferentJVMusingthevm

command-lineoption.Hereishowyoumightdothisona

Windowsmachine:



D:\tools\eclipse\eclipse.exe-vm"C:\ProgramFiles\Java\jdk1.5.

-vmargs-Xmx512M

























OrunderLinux,youmightdosomethinglikethis:



$/usr/local/eclipse/eclipse-vm/usr/lib/jvm/java-1.5.0-sun/b

-vmargs-Xmx512M&

Forthesamereason,whenyourunyourcodefromwithin

Eclipse,youneedtouseaJava5JVM.IfyouhaveseveralJVMs

configuredinyourEclipsepreferences,makesureyouare

compilingandexecutingyourprojectinJava5.



19.5.BasicProfilingwithTPTP

Oneofthebestwaystocheckthatperformanceis(and

remains)uptoscratchistowritecomprehensiveperformanceorientedunit(or"integration,"ifyouprefer)testsforeachof

yourusecases.Inmyexperience,thisisalsooneofthebest

waysofisolatingandcorrectingperformanceissues.This

involveswritingsimpleperformance-orientedunittestsforyour

keybusinessfunctions.Thisapproachhastheadditional

advantageofprogressivelybuildingasuiteofregressiontests

forfuturedevelopment.Here,wegothroughthebasicsof

profilingwithTPTP,bylookingathowtoprofilethebehaviorof

anapplicationusingsimple,performance-orientedunittests.

Asarule,youshouldtrytoprofilecodethatisascloseas

possibletotheproductioncode.Manypeopleusemockobjects

toreplaceDAOs(DataAccessObjects)forunittests,anditcan

beapowerfultechniquetospeedupthedevelopmentlifecycle.

Ifyouusethistypeofapproach,byallmeans,runyour

profilingwiththesetests:itcanrevealusefulinformationabout

memoryusageandtestcoverage.However,theperformance

testsareoflimitedvalue,sinceperformanceinadatabaserelatedapplicationisoftendominatedbydatabase

performance,soanyseriousperformancetestingshouldbe

doneinthiscontext.Agoodcompromiseistorunperformance

testsagainstanembeddedJavadatabasesuchas

JavaDB/DerbyorHSQLDB—thiswillgiveyouanideaofhow

yourapplicationbehavesagainstarealdatabase,without

incurringtheoverheadofnetworktrafficorhavingtosetup

andmaintainyourowndedicatedtestdatabaseinstance.

Throughoutthischapter,wearegoingtotestasimpleweb

applicationthatmanagesadatabaseofmodelplanes.Inthis

webapplication,userscanconsultthelistofknownplanetypes,

selectaplanetype,andthenviewthecorrespondingmodel

planes.

Forourfirstprofilingexercise,wewanttomakesurethatthe



applicationhomepage,whichinvolvesdisplayingthelistofall

availableplanetypes,willnotpresentanyperformanceissues.

Thispagewillbeheavilyused,soitisimportantthatitcan

supportahighload.Let'sseehowwewoulddothisusingJUnit

andTPTPinEclipse.

Intheapplication,planetypesarerepresentedbythe

PlaneTypeclass.TheDAOclassforplanetypesimplementsthe

followinginterface:

publicinterfacePlaneTypeDAO{

PlaneTypefindById(longid);

ListfindAll();

publicvoidsave(PlaneTypeplaneType);

publicvoiddelete(PlaneTypeplaneType);

}



Tolistallavailableplanetypes,weneedtoinvokethe

findAll()method.Itisimportantthatthismethodalways

performsefficiently,withaminimumofSQLandinaminimum

oftime.BecauseweareusingJUnithere,wewilluseMike

Clark'sexcellentperformanceunittestinglibrary,JUnitPerf(see

Chapter28),toimplementsomesimpleperformancetestson

thismethod.Thefullunittestisshownhere:

CodeView:

publicclassModelPlaneDaoPerfTestsextendsTestCase{

privatePlaneTypeDAOdao;

publicModelPlaneDaoPerfTests(Stringvalue){

super(value);

}



publicvoidsetUp()throwsSQLException{

ApplicationContextctx=SpringUtilsTestConfig.getAppli

dao=(PlaneTypeDAO)ctx.getBean("planeTypeDAO");

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 19. Profiling Java Applications in Eclipse

Tải bản đầy đủ ngay(0 tr)

×