Tải bản đầy đủ - 0 (trang)
5 Java — All of the Above

5 Java — All of the Above

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

8.5Java—AlloftheAbove

Intheearly1990s,Dr.JamesGoslingandhisteamatSunMicrosystems

setouttocreateaprogramminglanguagethatwouldrunonany

computingplatform.Themantrawastocreatea"writeonce,run

anywhere"computerlanguage.In1995,Sunreleasedthefirstversionof

theJavaprogramminglanguage.Owingtoitsportabilityandopen

specifications,Javahasbecomeenormouslypopular.Javacodeis

runnableonvirtuallyallcomputerplatforms,fromthesmallesthandheld

devicestothelargestmainframes.ThetimingofJava'sarrivalcouldn't

havebeenbetter:Itisacross-platformlanguagethatwasdeployableat

theinceptionofwide-scaleInternet-basedcommerce,theperfectmodel

ofcross-platformcomputing.AlthoughJavaandsomeofitsfeatures

werebrieflyintroducedinChapter5,wenowgointomoredetail.

IfyouhaveeverstudiedtheJavaprogramminglanguage,youknowthat

theoutputfromtheJavacompilerisabinaryclassfile.Thisclassfileis

executablebyaJavaVirtualMachine(JVM),whichresemblesareal

machineinmanyrespects.Ithasprivatememoryareasaddressableonly

byprocessesrunningwithinthemachine.Italsohasitsownbonafide

instructionsetarchitecture.ThisISAisstack-basedtokeepthemachine

simpleandportabletopracticallyanycomputingplatform.

Ofcourse,aJavaVirtualMachineisn'tarealmachine.Itisalayerof

softwarethatsitsbetweentheoperatingsystemandtheapplication

program:abinaryclassfile.Classfilesincludevariablesaswellasthe

methods(procedures)formanipulatingthosevariables.

Figure8.11illustrateshowtheJVMisacomputingmachineinminiature

withitsownmemoryandmethodarea.Noticethatthememoryheap,

methodcode,and"nativemethodinterface"areasaresharedamongall

processesrunningwithinthemachine.



Figure8.11:TheJavaVirtual

Machine

Thememoryheapismainmemoryspacethatisallocatedand

deallocatedasdatastructuresarecreatedanddestroyedthroughthread

execution.Java'sdeallocationofheapmemoryis(indelicately)referred

toasgarbagecollection,whichtheJVM(insteadoftheoperatingsystem)

doesautomatically.TheJavanativemethodareaprovidesworkspacefor

binaryobjectsexternaltoJava,suchascompiledC++orassembly

languagemodules.TheJVMmethodareacontainsthebinarycode

requiredtoruneachapplicationthreadlivingintheJVM.Thisiswhere

theclassvariabledatastructuresandprogramstatementsrequiredby

theclassreside.Java'sexecutableprogramstatementsarestoredinan

intermediatecodecalledbytecode,alsointroducedinChapter5.

Javamethodbytecodeisexecutedwithinvariousthreadprocesses.

SeveralthreadprocessesarestartedautomaticallybytheJVM,themain

programthreadbeingoneofthem.Onlyonemethodcanbeactiveata

timeineachthread,andprogramsmayspawnadditionalthreadsto

provideconcurrency.Whenathreadinvokesamethod,itcreatesa

memoryframeforthemethod.Partofthismemoryframeisusedforthe

method'slocalvariables,andanotherpartforitsprivatestack.Afterthe

threadhasdefinedthemethodstack,itpushesthemethod'sparameters

andpointsitsprogramcountertothefirstexecutablestatementofthe

method.

EachJavaclasscontainsatypeofsymboltablecalledaconstantpool,

whichisanarraythatcontainsinformationaboutthedatatypeofeachof

thevariablesofaclassandtheinitialvalueofthevariable,aswellas



accessflagsforthevariable(e.g.,whetheritispublicorprivatetothe

class).Theconstantpoolalsocontainsseveralstructuresotherthan

thosedefinedbytheprogrammer.ThisiswhySunMicrosystemscalls

entriesintheconstantpool(thearrayelements)attributes.Amongthe

attributesofeveryJavaclass,onefindshousekeepingitemssuchasthe

nameoftheJavasourcefile,partofitsinheritancehierarchy,and

pointerstootherJVMinternaldatastructures.

ToillustratehowtheJVMexecutesmethodbytecode,considertheJava

programshowninFigure8.12.

publicclassSimple{

publicstaticvoidmain(String[]args){

inti=0;

doublej=o;

while(i<10){

i=i+1;

j=j+1.0;

}//while

}//main()

}//Simple()

Figure8.12:ASimpleJavaProgram

Javarequiresthesourcecodeforthisclasstobestoredinatextfile

namedSimple.java.TheJavacompilerreadsSimple.javaanddoesall

thethingsthatothercompilersdo.Itsoutputisabinarystreamof

bytecodenamedSimple.class.TheSimple.classfilecanberunbyany

JVMofequalorlaterversionthanthatofthecompilerthatcreatedthe

class.ThesestepsareshowninFigure8.13.







Figure8.13:JavaClassCompilationandExecution

Atexecutiontime,aJavaVirtualMachinemustberunningonthehost

system.WhentheJVMloadsaclassfile,thefirstthingitdoesisverify

theintegrityofthebytecodebycheckingtheclassfileformat,checking

theformatofthebytecodeinstructions,andmakingsurethatnoillegal

referencesaremade.Afterthispreliminaryverificationissuccessfully

completed,theloaderperformsanumberofrun-timechecksasitplaces

thebytecodeinmemory.

Afterallverificationstepshavebeencompleted,theloaderinvokesthe

bytecodeinterpreter.Thisinterpreterhassixphasesinwhichitwill:

1. Performalinkeditofthebytecodeinstructionsbyaskingthe

loadertosupplyallreferencedclassesandsystembinaries,if

theyarenotalreadyloaded.

2. Createandinitializethemainstackframeandlocalvariables.

3. Createandstartexecutionthread(s).

4. Whilethethreadsareexecuting,manageheapstorageby

deallocatingunusedstorage.

5. Aseachthreaddies,deallocateitsresources.

6. Uponprogramtermination,killanyremainingthreadsand

terminatetheJVM.

Figure8.14showsthehexadecimalimageofthebytecodefor

Simple.class.Theaddressofeachbytecanbefoundbyaddingthevalue

inthefirst(shaded)columntotherowoffsetinthefirst(shaded)row.For

convenience,wehavetranslatedthebytecodeintocharacterswherethe

binaryvaluehasameaningful7-bitASCIIvalue.Youcanseethename

ofthesourcefile,Simple.java,beginningataddress06Dh.Thenameof

theclassstartsat080h.ReadersfamiliarwithJavaareawarethatthe

Simpleclassisalsoknownas.thisclass,anditssuperclassis

java.lang.Object,thenameofwhichstartsataddress089h.





Figure8.14:BinaryImageofSimple.class

NoticethatourclassfilebeginswiththehexnumberCAFEBABE.Itisthe

magicnumberindicatingthestartofaclassfile(andyes,itispolitically

incorrect!).An8-bytesequenceindicatingthelanguageversionofthe

classfilefollowsthemagicnumber.Ifthissequencenumberisgreater

thantheversionthattheinterpretingJVMcansupport,theverifier

terminatestheJVM.

Theexecutablebytecodebeginsataddress0E6h.Thehexdigits,16,at

address0E5hlettheinterpreterknowthattheexecutablemethod

bytecodeis22byteslong.Asinassemblylanguages,eachexecutable

bytecodehasacorrespondingmnemonic.Javacurrentlydefines204

differentbytecodeinstructions.Hence,onlyonebyteisneededforthe

entirerangeofopcodes.Thesesmallopcodeshelptokeepclasses

small,makingthemfasttoloadandeasilyconvertibletobinary

instructionsonthehostsystem.

Becausecertainsmallconstantsareusedsofrequentlyincomputer

programs,bytecodeshavebeendefinedespeciallytoprovidethese

constantswhereneeded.Forexample,themnemoniciconst_5pushes

theinteger5ontothestack.Inordertopushlargerconstantsontothe

stack,twobytecodesarerequired,thefirstfortheoperation,thesecond

fortheoperand.Aswementionedabove,localvariablesforeachclass

arekeptinanarray.Characteristically,thefirstfewelementsofthisarray

arethemostactive,sotherearebytecodesparticulartoaddressing

theseinitiallocalarrayelements.Accesstootherpositionsinthearray

requiresa2-byteinstruction:onefortheopcodeandthesecondforthe

offsetofthearrayelement.



Thatbeingsaid,letuslookatthebytecodeforthemain()methodof

Simple.class.WehaveextractedthebytecodefromFigure8.14and

listeditinFigure8.15alongwithmnemonicsandsomecommentary.The

leftmostcolumngivestherelativeaddressofeachinstruction.The

thread-specificprogramcounterusesthisrelativeaddresstocontrol

programflow.Wenowtracetheexecutionofthisbytecodesoyoucan

seehowitworks.





Figure8.15:AnnotatedBytecodeforSimple.class

Whentheinterpreterbeginsrunningthiscode,thePCisinitiallysetto

zeroandtheiconst_0instructionisexecuted.Thisistheexecutionofthe

inti=0;statementinthethirdlineoftheSimple.javasourcecode.The

PCisincrementedbyoneandsubsequentlyexecuteseachinitialization

instructionuntilitencountersthegotostatementatinstruction4.This

instructionaddsadecimal11totheprogramcounter,soitsvalue

becomes0Fh,whichpointstotheload_1instruction.

Atthispoint,theJVMhasassignedinitialvaluestoiandjandnow



proceedstochecktheinitialconditionofthewhilelooptoseewhether

theloopbodyshouldbeexecuted.Todothis,itplacesthevalueofi

(fromthelocalvariablearray)ontothestack,andthenitpushesthe

comparisonvalue0Ah.Notethatthisisalittlebitofcodeoptimization

thathasbeendoneforusbythecompiler.Bydefault,Javastoresinteger

valuesin32bits,thusoccupying4bytes.However,thecompilerissmart

enoughtoseethatthedecimalconstant10issmallenoughtostorein

onebyte,soitwrotecodetopushasinglebyteratherthanfourbytes

ontothestack.

Thecomparisonoperationinstruction,if_icmplt,popsiand0Ahand

comparestheirvalues(theltattheendofthemnemonicmeansthatitis

lookingforthelessthancondition).Ifiislessthan10,0Bhissubtracted

fromthePC,giving7,whichisthestartingaddressforthebodyofthe

loop.Whentheinstructionswithintheloopbodyhavebeencompleted,

executionfallsthroughtotheconditionalprocessingataddress0Fh.

Oncethisconditionbecomesfalse,theinterpreterreturnscontroltothe

operatingsystem,afterdoingsomecleanup.

Javaprogrammerswhohavewonderedhowtheinterpreterknowswhich

sourcelinehascausedaprogramcrashwillfindtheiranswerstartingat

address108hinthebinaryclassfileimageofFigure8.14.Thisisthe

beginningofthelinenumbertablethatassociatestheprogramcounter

valuewithaparticularlineinthesourceprogram.Thetwobytesstarting

ataddress106htelltheJVMthattherearesevenentriesintheline

numbertablethatfollows.Byfillinginafewdetails,wecanbuildthe

cross-referenceshowninFigure8.16.



PC



00

02

04

07

0B

0F



Source

Line#

1

2

3

4

5

6

7



PublicclassSimple{

Publicstaticvoidmain(String[]args){

inti=0;

doublej=0;

while(i<10){

i=i+1;

j=j+1.0;



15 8

9

A



}//while

}//main()

}//Simple



Figure8.16:AProgramCountertoSourceLine-Cross-Referencefor

Simple.class

NoticethatiftheprogramcrasheswhenthePC=9,forexample,the

offendingsourceprogramlinewouldbeline6.Interpretationofthe

bytecodegeneratedforsourcecodelinenumber7beginswhenthePC

isgreaterthanorequalto0Bh,butlessthan0Fh.

BecausetheJVMdoessomuchasitloadsandexecutesitsbytecode,its

performancecannotpossiblymatchtheperformanceofacompiled

language.ThisistrueevenwhenspeedupsoftwarelikeJava'sJust-InTime(JIT)compilerisused.Thetradeoff,however,isthatclassfilescan

becreatedandstoredononeplatformandexecutedonacompletely

differentplatform.Forexample,wecanwriteandcompileaJava

programonanAlphaRISCserveranditwillrunjustaswellonCISC

Pentium-classclientsthatdownloadtheclassfilebytecode.This"writeonce,run-anywhere"paradigmisofenormousbenefitforenterpriseswith

disparateandgeographicallyseparatesystems.Javaapplets(bytecode

thatrunsinbrowsers)areessentialforWeb-basedtransactionsandecommerce.Ultimately,allthatisrequiredoftheuseristoberunning

(reasonably)currentbrowsersoftware.Givenitsportabilityandrelative

easeofuse,theJavalanguageanditsvirtualmachineenvironmentare

theidealmiddlewareplatform.











8.6DatabaseSoftware

Byfar,themostpreciousassetsofanenterprisearenotitsofficesorits

factories,butitsdata.Regardlessofthenatureoftheenterprise—beita

privatebusiness,aneducationalinstitution,oragovernmentagency—the

definitiverecordofitshistoryandcurrentstateisimprinteduponitsdata.

Ifthedataisinconsistentwiththestateoftheenterprise,orifthedatais

inconsistentwithitself,itsusefulnessisquestionable,andproblemsare

certaintoarise.

Anycomputersystemsupportinganenterpriseistheplatformfor

interrelatedapplicationprograms.Theseprogramsperformupdateson

thedatainaccordancewithchangestothestateoftheenterprise.

Groupsofinterrelatedprogramsareoftenreferredtoasapplication

systems,becausetheyworktogetherasanintegratedwhole:Fewpieces

areveryusefulstandingontheirown.Applicationsystemcomponents

sharethesamesetofdata,andtypically,butnotnecessarily,sharethe

samecomputingenvironment.Today,applicationsystemsusemany

platforms:desktopmicrocomputers,fileservers,andmainframes.With

cooperativeWeb-basedcomputingcomingintovogue,sometimeswe

don'tknoworevencarewheretheapplicationisrunning.Althougheach

platformbringsitsuniquebenefitsandchallengestothescienceofdata

management,thefundamentalconceptsofdatabasemanagement

softwarehavebeenunchangedformorethanthreedecades.

Earlyapplicationsystemsrecordeddatausingmagnetictapeorpunched

cards.Bytheirsequentialnature,tapeandpunchedcardupdateshadto

berunasagroup,inbatchprocessingmode,forefficiency.Becauseany

dataelementonmagneticdiskscanbeaccesseddirectly,batch

processingofupdatesagainstflatfileswasnolongerforcedbythe

systemsarchitecture.However,oldhabitsarehardtobreak,and

programsarecostlytorewrite.Hence,flatfileprocessingpersistedyears

aftermostcardreadersbecamemuseumpieces.

Inflatfilesystems,eachapplicationprogramisfreetodefinewhatever

dataobjectsitneeds.Forthisreason,aconsistentviewofthesystemis

hardtoenforce.Forexample,let'ssaywehaveanaccountsreceivable

system,whichisanapplicationsystemthatkeepstrackofwhoowesus



howmuchmoneyandforhowlongithasbeenowed.Theprogramthat

producesmonthlyinvoicesmaypostmonthlytransactionstoa6-digit

field(ordataelement)calledCUST_OWE.Now,thepersondoingthe

monthlyreconciliationscouldjustaswellcallthisfieldCUST_BAL,and

maybeexpectingittobefivedigitswide.Itisalmostcertainthat

somewherealongtheline,informationwillbelostandconfusionwill

reign.Sometimeduringthemonth,afterseveralthousanddollarsare

"unaccountedfor,"thedebuggerswilleventuallyfigureoutthat

CUST_OWEisthesamedataelementasCUST_BAL,andthatthe

problemwascausedbytruncationorafieldoverflowcondition.

Databasemanagementsystems(DBMSs)werecreatedtopreventthese

predicaments.Theyenforceorderandconsistencyuponfile-based

applicationsystems.Withdatabasesystems,nolongerareprogrammers

freetodescribeandaccessadataelementinanymannertheyplease.

Thereisone—andonlyone—definitionofthedataelementsina

databasemanagementsystem.Thisdefinitionisasystem'sdatabase

schema.Onsomesystems,adistinctionismadebetweenthe

programmer'sviewofthedatabase,itslogicalschema,andthecomputer

system'sviewofthedatabase,calleditsphysicalschema.Thedatabase

managementsystemintegratesthephysicalandlogicalviewsofthe

database.Applicationprogramsemploythelogicalschemapresentedby

thedatabasemanagementsystemtoreadandupdatedatawithinthe

physicalschema,undercontrolofthedatabasemanagementsystemand

theoperatingsystem.Figure8.17illustratesthisrelationship.



Figure8.17:TheRelationshipofa

DatabaseManagementSystemtoOtherSystem



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

5 Java — All of the Above

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

×