Tải bản đầy đủ - 0 (trang)
Chapter 1.  A Modern Language

Chapter 1.  A Modern Language

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

whyithasbecomedominantintheworldofprogramming

today.



1.1.EnterJava

TheJavaprogramminglanguage,developedatSun

MicrosystemsundertheguidanceofNetluminariesJames

GoslingandBillJoy,isdesignedtobeamachine-independent

programminglanguagethatisbothsafeenoughtotraverse

networksandpowerfulenoughtoreplacenativeexecutable

code.Javaaddressestheissuesraisedhereandhelpsusstart

buildingthekindsofapplicationswewant.

Initially,mostoftheenthusiasmforJavacenteredonits

capabilitiesforbuildingembeddedapplicationsfortheWeb

calledapplets.Butintheearlydays,appletsandotherclientsideGUIapplicationswritteninJavawerelimited.Today,Java

hasSwing,oneofthemostsophisticatedtoolkitsforbuilding

graphicaluserinterfaces(GUIs)inanylanguage.This

developmenthasallowedJavatobecomeapopularplatformfor

developingtraditionalclient-sideapplicationsoftware.

Ofevenmoreimportanceinthepastfewyears,Javahas

becomethepremierplatformforweb-basedapplicationsand

webservices.Theseapplicationsusetechnologiesincludingthe

JavaServletAPI,EnterpriseJavaBeans?,andmanypopular

opensourceandcommercialJavaapplicationserversand

frameworks.Java'sportabilityandspeedmakeittheplatform

ofchoiceformodernbusinessapplications.

ThisbookwillshowyouhowtouseJavatoaccomplishallof

thesereal-worldprogrammingtasks.Inthecomingchapters

we'llcovereverythingfromtextprocessingtonetworking,

buildingrichclient-sideGUIapplicationswithSwingand

lightweightweb-basedapplicationswithXML.



1.1.1.Java'sOrigins



TheseedsofJavawereplantedin1990bySunMicrosystems

patriarchandchiefresearcher,BillJoy.Atthetime,Sunwas

competinginarelativelysmallworkstationmarketwhile

Microsoftwasbeginningitsdominationofthemore

mainstream,Intel-basedPCworld.WhenSunmissedtheboat

onthePCrevolution,JoyretreatedtoAspen,Coloradotowork

onadvancedresearch.Hewascommittedtotheideaof

accomplishingcomplextaskswithsimplesoftwareandfounded

theaptlynamedSunAspenSmallworks.

Oftheoriginalmembersofthesmallteamofprogrammers

assembledinAspen,JamesGoslingwillberememberedasthe

fatherofJava.Goslingfirstmadeanameforhimselfinthe

early80sastheauthorofGoslingEmacs,thefirstversionof

thepopularEmacseditorthatwaswritteninCandranunder

Unix.GoslingEmacsbecamepopularbutwassooneclipsedby

afreeversion,GNUEmacs,writtenbyEmacs'soriginal

designer.Bythattime,GoslinghadmovedontodesignSun's

NeWS,whichbrieflycontendedwiththeXWindowSystemfor

controloftheUnixGUIdesktopin1987.Althoughsomepeople

wouldarguethatNeWSwassuperiortoX,NeWSlostbecause

Sunkeptitproprietaryanddidn'tpublishsourcecodewhilethe

primarydevelopersofXformedtheXConsortiumandtookthe

oppositeapproach.

DesigningNeWStaughtGoslingthepowerofintegratingan

expressivelanguagewithanetwork-awarewindowingGUI.It

alsotaughtSunthattheInternetprogrammingcommunitywill

ultimatelyrefusetoacceptproprietarystandards,nomatter

howgoodtheymaybe.TheseedsofJava'slicensingscheme

andopen(ifnotquite"opensource")codeweresownby

NeWS'sfailure.GoslingbroughtwhathehadlearnedtoBill

Joy'snascentAspenproject.In1992,workontheprojectledto

thefoundingoftheSunsubsidiary,FirstPerson,Inc.Itsmission

wastoleadSunintotheworldofconsumerelectronics.

TheFirstPersonteamworkedondevelopingsoftwarefor

informationappliances,suchascellularphonesandpersonal



digitalassistants(PDAs).Thegoalwastoenablethetransferof

informationandreal-timeapplicationsovercheapinfraredand

packet-basednetworks.Memoryandbandwidthlimitations

dictatedsmall,efficientcode.Thenatureoftheapplications

alsodemandedtheybesafeandrobust.Goslingandhis

teammatesbeganprogramminginC++,buttheysoonfound

themselvesconfoundedbyalanguagethatwastoocomplex,

unwieldy,andinsecureforthetask.Theydecidedtostartfrom

scratch,andGoslingbeganworkingonsomethinghedubbed

"C++minusminus."

WiththefounderingoftheAppleNewton,itbecameapparent

thatthePDA'sshiphadnotyetcomein,soSunshifted

FirstPerson'seffortstointeractiveTV(ITV).Theprogramming

languageofchoiceforITVset-topboxeswastobethenear

ancestorofJava,alanguagecalledOak.Evenwithitselegance

andabilitytoprovidesafeinteractivity,Oakcouldnotsalvage

thelostcauseofITVatthattime.Customersdidn'twantit,and

Sunsoonabandonedtheconcept.

Atthattime,JoyandGoslinggottogethertodecideonanew

strategyfortheirinnovativelanguage.Itwas1993,andthe

explosionofinterestintheWebpresentedanewopportunity.

Oakwassmall,safe,architecture-independent,andobjectoriented.Asithappens,thesearealsosomeofthe

requirementsforauniversal,Internet-savvyprogramming

language.Sunquicklychangedfocus,and,withalittle

retooling,OakbecameJava.



1.1.2.GrowingUp

ItwouldnotbeoverdoingittosaythatJavacaughtonlike

wildfire.EvenbeforeitsfirstofficialreleasewhenJavawasstill

anonproduct,nearlyeverymajorindustryplayerhadjumped

ontheJavabandwagon.JavalicenseesincludedMicrosoft,

Intel,IBM,andvirtuallyallmajorhardwareandsoftware



vendors.That'snottosaythateverythingwaseasy.Evenwith

allthissupport,Javatookalotofknocksandhadsomegrowing

painsduringitsfirstfewyears.

Aseriesofbreechofcontractandantitrustlawsuitsbetween

SunandMicrosoftoverthedistributionofJavaanditsusein

InternetExplorerhashampereditsdeploymentontheworld's

mostcommondesktopoperatingsystemWindows.Microsoft's

involvementwithJavaalsobecomeonefocusofalargerfederal

lawsuitoverseriousanticompetitivepracticesatthecompany,

withcourttestimonyrevealingconcertedeffortsbythesoftware

gianttoundermineJavabyintroducingincompatibilitiesinits

versionofthelanguage.Meanwhile,Microsoftintroducedits

ownJava-likelanguagecalledC#(C-sharp)aspartofits.NET

initiativeanddroppedJavafrominclusioninthelatestversions

ofWindows.

ButJavacontinuestospreadonbothhigh-andlow-end

platforms.AswebeginlookingattheJavaarchitecture,you'll

seethatmuchofwhatisexcitingaboutJavacomesfromthe

self-contained,virtualmachineenvironmentinwhichJava

applicationsrun.Javahasbeencarefullydesignedsothatthis

supportingarchitecturecanbeimplementedeitherinsoftware,

forexistingcomputerplatforms,orincustomizedhardware,for

newkindsofdevices.Sunandotherindustrygiantsare

producingfastJavachipsandmicroprocessorstailoredtorun

media-richJavaapplications.HardwareimplementationsofJava

arecurrentlyusedinsmartcardsandotherembeddedsystems.

Todayyoucanbuy"wearable"devices,suchasringsanddog

tags,thathaveJavainterpretersembeddedinthem.Software

implementationsofJavaareavailableforallmoderncomputer

platformsdowntoportablecomputingdevices,suchasthe

popularPalmPDA.Javaisalsobecomingstandardequipment

onmanynewcellphones.



1.2.AVirtualMachine

Javaisbothacompiledandaninterpretedlanguage.Java

sourcecodeisturnedintosimplebinaryinstructions,muchlike

ordinarymicroprocessormachinecode.However,whereasCor

C++sourceisreducedtonativeinstructionsforaparticular

modelofprocessor,Javasourceiscompiledintoauniversal

formatinstructionsforavirtualmachine.

CompiledJavabytecodeisexecutedbyaJavaruntime

interpreter.Theruntimesystemperformsallthenormal

activitiesofarealprocessor,butitdoessoinasafe,virtual

environment.Itexecutesastack-basedinstructionsetand

managesmemorylikeanoperatingsystem.Itcreatesand

manipulatesprimitivedatatypesandloadsandinvokesnewly

referencedblocksofcode.Mostimportantly,itdoesallthisin

accordancewithastrictlydefinedopenspecificationthatcanbe

implementedbyanyonewhowantstoproduceaJava-compliant

virtualmachine.Together,thevirtualmachineandlanguage

definitionprovideacompletespecification.Thereareno

featuresofthebaseJavalanguageleftundefinedor

implementation-dependent.Forexample,Javaspecifiesthe

sizesandmathematicalpropertiesofallitsprimitivedatatypes

ratherthanleavingituptotheplatformimplementation.

TheJavainterpreterisrelativelylightweightandsmall;itcanbe

implementedinwhateverformisdesirableforaparticular

platform.Theinterpretermayberunasaseparateapplication,

oritcanbeembeddedinanotherpieceofsoftware,suchasa

webbrowser.Puttogether,thismeansthatJavacodeis

implicitlyportable.ThesameJavaapplicationbytecodecanrun

onanyplatformthatprovidesaJavaruntimeenvironment,as

showninFigure1-1.Youdon'thavetoproducealternative

versionsofyourapplicationfordifferentplatforms,andyou

don'thavetodistributesourcecodetoendusers.



Figure1-1.TheJavaruntimeenvironment



ThefundamentalunitofJavacodeistheclass.Asinother

object-orientedlanguages,classesareapplicationcomponents

thatholdexecutablecodeanddata.CompiledJavaclassesare

distributedinauniversalbinaryformatthatcontainsJava

bytecodeandotherclassinformation.Classescanbe

maintaineddiscretelyandstoredinfilesorarchiveslocallyoron

anetworkserver.Classesarelocatedandloadeddynamicallyat

runtimeastheyareneededbyanapplication.

Inadditiontotheplatform-specificruntimesystem,Javahasa

numberoffundamentalclassesthatcontainarchitecturedependentmethods.Thesenativemethodsserveasthe

gatewaybetweentheJavavirtualmachineandtherealworld.

Theyareimplementedinanativelycompiledlanguageonthe

hostplatformandprovidelow-levelaccesstoresourcessuchas



thenetwork,thewindowingsystem,andthehostfilesystem.

ThevastmajorityofJava,however,iswritteninJava

itselfbootstrappedfromthesebasicprimitivesandistherefore

portable.ThisincludesfundamentalJavatoolssuchastheJava

compiler,webbrowsercomponents,andthesophisticatedGUI

libraries,whicharealsowritteninJavaandaretherefore

availableonallJavaplatformsinexactlythesamewaywithout

porting.

Historically,interpretershavebeenconsideredslow,butJavais

notatraditionalinterpretedlanguage.Inadditiontocompiling

sourcecodedowntoportablebytecode,Javahasalsobeen

carefullydesignedsothatsoftwareimplementationsofthe

runtimesystemcanfurtheroptimizetheirperformanceby

compilingbytecodetonativemachinecodeonthefly.Thisis

calledjust-in-time(JIT)ordynamiccompilation.WithJIT

compilation,Javacodecanexecuteasfastasnativecodeand

maintainitstransportabilityandsecurity.

Thisisanoftenmisunderstoodpointamongthosewhowantto

comparelanguageperformance.Thereisonlyoneintrinsic

performancepenaltythatcompiledJavacodesuffersatruntime

forthesakeofsecurityandvirtualmachinedesignarraybounds

checking.Everythingelsecanbeoptimizedtonativecodejust

asitcanwithastaticallycompiledlanguage.Goingbeyond

that,theJavalanguageincludesmorestructuralinformation

thanmanyotherlanguages,providingmoreroomfor

optimizations.Alsorememberthattheseoptimizationscanbe

madeatruntime,takingintoaccounttheactualapplication

behaviorandcharacteristics.Whatcanbedoneatcompiletime

thatcan'tbedonebetteratruntime?Well,thereisatradeoff:

time.

TheproblemwithatraditionalJITcompilationisthatoptimizing

codetakestime.SoaJITcompilercanproducedecentresults

butmaysufferasignificantlatencywhentheapplicationstarts

up.Thisisgenerallynotaproblemforlong-runningserver-side

applicationsbutisaseriousproblemforclient-sidesoftware



andapplicationsrunonsmallerdeviceswithlimitedcapabilities.

Toaddressthis,Sun'scompilertechnology,calledHotSpot,uses

atrickcalledadaptivecompilation.Ifyoulookatwhat

programsactuallyspendtheirtimedoing,itturnsoutthatthey

spendalmostalltheirtimeexecutingarelativelysmallpartof

thecodeagainandagain.Thechunkofcodethatisexecuted

repeatedlymaybeonlyasmallfractionofthetotalprogram,

butitsbehaviordeterminestheprogram'soverallperformance.

AdaptivecompilationalsoallowstheJavaruntimetotake

advantageofnewkindsofoptimizationsthatsimplycan'tbe

doneinastaticallycompiledlanguage,hencetheclaimthat

JavacodecanrunfasterthanC/C++insomecases.

Totakeadvantageofthisfact,HotSpotstartsoutasanormal

Javabytecodeinterpreter,butwithadifference:itmeasures

(profiles)thecodeasitisexecutingtoseewhatpartsarebeing

executedrepeatedly.Onceitknowswhichpartsofthecodeare

crucialtoperformance,HotSpotcompilesthosesectionsinto

optimalnativemachinecode.Sinceitcompilesonlyasmall

portionoftheprogramintomachinecode,itcanaffordtotake

thetimenecessarytooptimizethoseportions.Therestofthe

programmaynotneedtobecompiledatalljust

interpretedsavingmemoryandtime.Infact,Sun'sdefaultJava

VMcanruninoneoftwomodes:clientandserver,whichtellit

whethertoemphasizequickstartuptimeandmemory

conservationorflatoutperformance.

Anaturalquestiontoaskatthispointis,Whythrowawayall

thisgoodprofilinginformationeachtimeanapplicationshuts

down?Well,Sunhaspartiallybroachedthistopicwiththe

releaseofJava5.0throughtheuseofshared,read-onlyclasses

thatarestoredpersistentlyinanoptimizedform.This

significantlyreducesboththestartuptimeandoverheadof

runningmanyJavaapplicationsonagivenmachine.The

technologyfordoingthisiscomplex,buttheideaissimple:

optimizethepartsoftheprogramthatneedtogofast,and

don'tworryabouttherest.



1.3.JavaComparedwithOtherLanguages

Javaisarelativelynewlanguage,butitdrawsonmanyyearsof

programmingexperiencewithotherlanguagesinitschoiceof

features.ItisworthtakingamomenttocompareJavaatahigh

levelwithsomeotherpopularlanguagestoday,bothforthe

benefitofthoseofyouwithotherprogrammingexperienceand

forthenewcomerswhoneedtoputthingsincontext.Wedo

notexpectyoutohaveaknowledgeofanyparticular

programminglanguageinthisbookandwhenwerefertoother

languagesbywayofcomparisonwehopethatthecomments

areself-explanatory.

Atleastthreepillarsarenecessarytosupportauniversal

programminglanguagetoday:portability,speed,andsecurity.

Figure1-2showshowJavacomparestoacoupleofother

languages.



Figure1-2.Programminglanguagescompared



YoumayhaveheardthatJavaisalotlikeCorC++,butthat's

reallynottrue,exceptatasuperficiallevel.Whenyoufirstlook



atJavacode,you'llseethatthebasicsyntaxlookslikeCor

C++.Butthat'swherethesimilaritiesend.Javaisbynomeans

adirectdescendantofCoranext-generationC++.Ifyou

comparelanguagefeatures,you'llseethatJavaactuallyhas

moreincommonwithhighlydynamiclanguagessuchas

SmalltalkandLisp.Infact,Java'simplementationisaboutas

farfromnativeCasyoucanimagine.

Thesurface-levelsimilaritiestotheselanguagesareworth

noting,however.JavaborrowsheavilyfromCandC++syntax,

soyou'llseeterselanguageconstructs,includinganabundance

ofcurlybracesandsemicolons.JavasubscribestotheC

philosophythatagoodlanguageshouldbecompact;inother

words,itshouldbesufficientlysmallandregularsoa

programmercanholdallthelanguage'scapabilitiesinhisorher

headatonce.JustasCisextensiblewithlibraries,packagesof

Javaclassescanbeaddedtothecorelanguagecomponentsto

extenditsvocabulary.

Chasbeensuccessfulbecauseitprovidesareasonablyfeaturepackedprogrammingenvironment,withhighperformanceand

anacceptabledegreeofportability.Javaalsotriestobalance

functionality,speed,andportability,butitdoessoinavery

differentway.Ctradesfunctionalityforportability;Javainitially

tradedspeedforportability.Javaalsoaddressessecurityissues

whileCdoesn't.

IntheearlydaysbeforeJITandadaptivecompilation,Javawas

slowerthanstaticallycompiledlanguagesandtherewasa

constantrefrainfromdetractorsthatitwouldnevercatchup.

Butaswedescribedintheprevioussection,Java'sperformance

isnowcomparabletoCorC++forequivalenttasksandthose

criticismshavegenerallyfallenquiet.Infact,in2004,ID

Software'sopensourceQuake2videogameenginewasported

toJava.IfJavaisfastenoughforfirst-person-shootervideo

games,it'scertainlyfastenoughforbusinessapplications.

Scriptinglanguages,suchasPerl,Python,andRuby,arevery



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

Chapter 1.  A Modern Language

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

×