Lucky Seven Neuerungen in Java 7 Wolfgang Weigend Oracle - - PowerPoint PPT Presentation

lucky seven
SMART_READER_LITE
LIVE PREVIEW

Lucky Seven Neuerungen in Java 7 Wolfgang Weigend Oracle - - PowerPoint PPT Presentation

Lucky Seven Neuerungen in Java 7 Wolfgang Weigend Oracle Deutschland B.V. & Co. KG P NeuerungeninJava7 <InsertPictureHere> Diewichtigsten nderungen,Erweiterungen


slide-1
SLIDE 1

Lucky Seven

Neuerungen in Java 7

Wolfgang Weigend

Oracle Deutschland B.V. & Co. KG

slide-2
SLIDE 2

<InsertPictureHere>

NeuerungeninJava7 Diewichtigsten Änderungen,Erweiterungen

P

  • WolfgangWeigend

SystemberaterJavaTechnologieundArchitektur

slide-3
SLIDE 3

PrioritiesfortheJavaPlatforms

GrowDeveloperBase GrowAdoption IncreaseCompetitiveness IncreaseCompetitiveness Adapttochange

slide-4
SLIDE 4

JavaCommunities

slide-5
SLIDE 5

HowJavaEvolvesandAdapts

CommunityDevelopmentof JavaTechnologySpecifications

slide-6
SLIDE 6

JCPReforms

  • Developers voiceintheExecutiveCommittee
  • SOUJava
  • GoldmanSachs
  • LondonJavaCommunity
  • AlexTerrazas
  • JCPstartingaprogramofreform
  • JCPstartingaprogramofreform
  • JSR348:TowardsanewversionoftheJCP
slide-7
SLIDE 7

EvolvingtheLanguage

From“EvolvingtheJavaLanguage” - JavaOne2005

  • Javalanguageprinciples

– Readingismoreimportantthanwriting – Codeshouldbeajoytoread – Thelanguageshouldnothidewhatishappening – Codeshoulddowhatitseemstodo – Simplicitymatters – Every“good” featureaddsmore“bad” weight 6

6

– Every“good” featureaddsmore“bad” weight – Sometimesitisbesttoleavethingsout

  • Onelanguage:withthesamemeaningeverywhere
  • Nodialects
  • WewillevolvetheJavalanguage
  • Butcautiously,withalongtermview
  • “firstdonoharm”
slide-8
SLIDE 8

Soyouwanttochangethelanguage?

7

7

slide-9
SLIDE 9

JavaSE7ReleaseContents

  • JavaLanguage
  • ProjectCoin(JSR-334)
  • ClassLibraries
  • NIO2(JSR-203)
  • Fork-Joinframework,ParallelArray (JSR-166y)

8

8

  • Fork-Joinframework,ParallelArray (JSR-166y)
  • JavaVirtualMachine
  • TheDaVinci Machineproject(JSR-292)
  • InvokeDynamic bytecode
  • MiscellaneousThings
  • JSR-336:JavaSE7ReleaseContents
slide-10
SLIDE 10

<InsertPictureHere>

Section Divider

Small Small Language Language

9

9

Language Language Changes Changes

ProjectCoin ProjectCoin

slide-11
SLIDE 11

ProjectCoinConstraints

  • Small languagechanges
  • Smallinspecification,implementation,testing
  • Nonewkeywords!
  • Waryoftypesystemchanges

Coordinatewithlargerlanguagechanges

10

10

  • Coordinatewithlargerlanguagechanges

– ProjectLambda – Modularity

  • Onelanguage,onejavac
slide-12
SLIDE 12

BetterIntegerLiteral

  • Binaryliterals

intmask=0b101010101010;

11

11

  • Withunderscoresforclarity

intmask=0b1010_1010_1010; longbig=9_223_783_036_967_937L;

slide-13
SLIDE 13

StringSwitchStatement

  • Todaycaselabelincludesintegerconstantsand

enumconstants

  • Stringsareconstantstoo(immutable)

12

12

slide-14
SLIDE 14

DistinguishStringsToday

intmonthNameToDays(Strings,intyear){ if("April".equals(s)||"June".equals(s)|| "September".equals(s)||"November".equals(s)) return30; if("January".equals(s)||"March".equals(s)||

13

13

if("January".equals(s)||"March".equals(s)|| "May".equals(s)||"July".equals(s)|| "August".equals(s)||"December".equals(s)) return31; if("February".equals(s)) ...

slide-15
SLIDE 15

StringsinSwitchStatements

intmonthNameToDays(Strings,intyear){ switch(s){ case"April":case"June": case"September":case"November": return30; case"January":case"March":

14

14

case"May":case"July": case"August":case"December": return31; case"February”: ... default: ...

slide-16
SLIDE 16

SimplifyingGenerics

  • Pre-generics

ListstrList=newArrayList();

15

15

slide-17
SLIDE 17

SimplifyingGenerics

  • Pre-generics

ListstrList=newArrayList();

  • WithGenerics

List<String> strList=newArrayList<String>();

16

16

List<String> strList=newArrayList<String>();

slide-18
SLIDE 18

SimplifyingGenerics

  • Pre-generics

ListstrList=newArrayList();

  • WithGenerics

List<String> strList=newArrayList<String>();

17

17

List<String> strList=newArrayList<String>(); List<Map<String,List<String>> strList= newArrayList<Map<String,List<String>>();

slide-19
SLIDE 19

DiamondOperator

  • Pre-generics

ListstrList=newArrayList();

  • WithGenerics

List<String> strList=newArrayList<String>();

18

18

  • Withdiamond(<>)compilerinferstype

List<Map<String,List<String>> strList= newArrayList<Map<String,List<String>>(); List<String> strList=newArrayList<>(); List<Map<String,List<String>> strList= newArrayList<>();

slide-20
SLIDE 20

CopyingaFile

InputStreamin=newFileInputStream(src); OutputStreamout=newFileOutputStream(dest); byte[]buf=newbyte[8192]; intn;

19

19

while(n=in.read(buf))>=0)

  • ut.write(buf,0,n);
slide-21
SLIDE 21

CopyingaFile(Better,butwrong)

InputStreamin=newFileInputStream(src); OutputStreamout=newFileOutputStream(dest); try{ byte[]buf=newbyte[8192];

20

20

intn; while(n=in.read(buf))>=0)

  • ut.write(buf,0,n);

}finally{ in.close();

  • ut.close();

}

slide-22
SLIDE 22

CopyingaFile(Correct,butcomplex)

InputStreamin=newFileInputStream(src); try{ OutputStreamout=newFileOutputStream(dest); try{ byte[]buf=newbyte[8192]; intn; while(n=in.read(buf))>=0)

21

21

while(n=in.read(buf))>=0)

  • ut.write(buf,0,n);

}finally{

  • ut.close();

} }finally{ in.close(); }

slide-23
SLIDE 23

CopyingaFile(Correct,butcomplex)

InputStreamin=newFileInputStream(src); try{ OutputStreamout=newFileOutputStream(dest); try{ byte[]buf=newbyte[8192]; intn; while(n=in.read(buf))>=0)

22

22

while(n=in.read(buf))>=0)

  • ut.write(buf,0,n);

}finally{

  • ut.close();

} }finally{ in.close(); }

Exceptionthrownfrom potentiallythreeplaces. Detailsoffirsttwocouldbelost

slide-24
SLIDE 24

AutomaticResourceManagement

try(InputStreamin=newFileInputStream(src), OutputStreamout=newFileOutputStream(dest)) { byte[]buf=newbyte[8192]; intn; while(n=in.read(buf))>=0)

23

23

while(n=in.read(buf))>=0)

  • ut.write(buf,0,n);

}

slide-25
SLIDE 25

TheDetails

  • Compilerde-sugarstry-with-resourcesintonestedtry-

finallyblockswithvariablestotrackexceptionstate

  • Suppressedexceptionsarerecordedforposterity

usinganewfacilityofThrowable

  • APIsupportinJDK7

24

24

  • APIsupportinJDK7
  • Newsuperinterfacejava.lang.AutoCloseable
  • AllAutoCloseable andbyextensionjava.io.Closeabletypes

useablewithtry-with-resources

  • Anythingwithavoidclose() methodisacandidate
  • JDBC4.1retro-fittedasAutoCloseable too
slide-26
SLIDE 26

MoreInformativeBacktraces

java.io.IOException atSuppress.write(Suppress.java:19) atSuppress.main(Suppress.java:8) Suppressed: java.io.IOException at Suppress.close(Suppress.java:24)

25

25

at Suppress.close(Suppress.java:24) at Suppress.main(Suppress.java:9) Suppressed: java.io.IOException at Suppress.close(Suppress.java:24) at Suppress.main(Suppress.java:9)

slide-27
SLIDE 27

VarargsWarnings

classTest{ publicstaticvoidmain(String...args){ List<List<String>>monthsInTwoLanguages= Arrays.asList(Arrays.asList("January", "February"), Arrays.asList("Enero", "Febrero")); 26

26

} } Test.java:7: warning: [unchecked] unchecked generic array creation for varargsparameter of type List<String>[] Arrays.asList(Arrays.asList("January", ^ 1 warning

slide-28
SLIDE 28

HeapPollution– JLSv34.12.2.1

  • Avariableofaparameterizedtypereferstoanobject

thatisnotofthatparameterizedtype

  • Forexample,thevariableoftypeList<String>[]

mightpointtoanarrayofListswheretheListsdid notcontainstrings

27

27

notcontainstrings

  • ReportspossiblelocationsofClassCastExceptions

atruntime

  • Aconsequenceoferasure
  • Possiblyproperlyaddressedbyreificationinthefuture
slide-29
SLIDE 29

VarargsWarningsRevised

  • Newmandatorycompilerwarningatsuspectvarargs

methoddeclarations

  • Byapplyinganannotationatthedeclaration,

warningsatthedeclarationandcallsites canbe suppressed

28

28

suppressed

  • @SuppressWarnings(value=“unchecked”)
  • @SafeVarargs
slide-30
SLIDE 30

LotsofExceptions

try{ ... }catch(ClassNotFoundExceptioncnfe){ doSomethingClever(cnfe); throwcnfe; }catch(InstantiationExceptionie){ log(ie); throwie;

29

29

throwie; }catch(NoSuchMethodExceptionnsme){ log(nsme); thrownsme; }catch(InvocationTargetExceptionite){ log(ite); throwite; }

slide-31
SLIDE 31

Multi-Catch

try{ ... }catch(ClassCastExceptione){ doSomethingClever(e); throwe; }catch(InstantiationException|

30

30

NoSuchMethodException| InvocationTargetExceptione){ log(e); throwe; }

slide-32
SLIDE 32

IDESupport

31

31

slide-33
SLIDE 33

32

32

slide-34
SLIDE 34

NewI/O2(NIO2)Libraries

  • OriginalJavaI/OAPIspresentedchallengesfordevelopers
  • Needsomethingbetterthanjava.io.File
  • Doesn'tworkconsistentlyacrossplatforms
  • Nousefulexceptionswhenafileoperationfails
  • Missingbasicoperations(filecopy,move,...)

JSR203

33

33

  • Missingbasicoperations(filecopy,move,...)
  • Limitedsupportforsymboliclinks
  • Limitedsupportforfileattributes,performanceissues
  • Nowaytoplug-inotherfilesystemimplementations
  • JavaNIO2solvestheseproblems
slide-35
SLIDE 35

JavaNIO2Features

  • PathisareplacementforFile

− Biggestimpactondevelopers

  • Betterdirectorysupport
  • Files

− Staticmethodstooperateonfilesanddirectories Supportforsymboliclinks

34

34

− Supportforsymboliclinks

  • FileStore

− Representsunderlyingfilestorage(partition,concretefilesystem)

  • FileSystem

− SPIinterfacetoafilesystem(FAT,ZFS,Ziparchive,network,etc)

  • Accesstofilemetadata
slide-36
SLIDE 36

Path Class

  • Equivalentofjava.io.File inthenewAPI

– Immutable

  • HavemethodstoaccessandmanipulatePath
  • Supportsoldlibraries

− CreateFilefromPathusingtoFile //Makeareferencetothepath

35

35

//Makeareferencetothepath Pathhome=Paths.get(“/home/fred”); //Resolvetmpfrom/home/fred->/home/fred/tmp PathtmpPath=home.resolve(“tmp”); //Createarelativepathfromtmp->.. PathrelativePath=tmpPath.relativize(home) Filefile=relativePath.toFile();

slide-37
SLIDE 37

FileOperation– Copy,Move

  • Filecopyisreallyeasy

– Withfinegraincontrol Pathsrc=Paths.get(“/home/fred/readme.txt”); Pathdst=Paths.get(“/home/fred/copy_readme.txt”); Files.copy(src,dst, StandardCopyOption.COPY_ATTRIBUTES,

36

36

  • Filemoveissupported

– Optionalatomicmovesupported StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); Pathsrc=Paths.get(“/home/fred/readme.txt”); Pathdst=Paths.get(“/home/fred/readme.1st”); Files.move(src,dst,StandardCopyOption.ATOMIC_MOVE);

slide-38
SLIDE 38

Directories

  • DirectoryStreamiterateoverentries

– Scalestolargedirectories – Useslessresources – Smoothoutresponsetimeforremotefilesystems – ImplementsIterable andCloseable forproductivity

  • Filteringsupport

Build-insupportforglob,regexandcustomfilters

37

37

– Build-insupportforglob,regexandcustomfilters PathsrcPath=Paths.get(“/home/fred/src”); try(DirectoryStream<Path>dir= srcPath.newDirectoryStream(“*.java”)){ for(Pathfile:dir) System.out.println(file.getName()); }

slide-39
SLIDE 39

ConcurrencyAPIs

  • JSR166y

− UpdatetoJSR166xwhichwasanupdatetoJSR166

  • Addsalightweighttaskframework

− AlsoreferredtoasFork/Join

  • 38

38

  • Phaser

− BarriersimilartoCyclicBarrier andCountDownLatch

  • TransferQueue interface

− ExtensiontoBlockingQueue − ImplementedbyLinkedTransferQueue

slide-40
SLIDE 40

ForkJoinFramework

  • Goalistotakeadvantageofmultipleprocessor
  • Designedfortaskthatcanbebrokendowninto

smallerpieces

– Eg.Fibonaccinumberfib(10)=fib(9)+fib(8)

  • Typicalalgorithmthatusesforkjoin

join fork 39

39

ifIcanmanagethetask performthetask else forktaskintox numberofsmaller/similartask jointheresults

join fork

slide-41
SLIDE 41

KeyClasses

  • ForkJoinPool

– ExecutorserviceforrunningForkJoinTask

  • ForkJoinTask

– Thebaseclassforforkjointask

  • RecursiveAction

– AsubclassofForkJoinTask Arecursiveresultlesstask

40

40

– Arecursiveresultlesstask – Implementscompute() abstractmethodtoperformcalculation

  • RecursiveTask

– SimilartoRecursiveAction butreturnsaresult

slide-42
SLIDE 42

ForkJoinExample– Fibonacci

publicclassFibonacciextendsRecursiveTask<Integer>{ privatefinalintnumber; publicFibonacci(intn){number=n;} @OverrideprotectedIntegercompute(){ switch(number){ case0:return(0); case1:return(1); default: 41

41

default: Fibonaccif1=newFibonacci(number– 1); Fibonaccif2=newFibonacci(number– 2); f1.fork();f2.fork(); return(f1.join()+f2.join()); } } }

slide-43
SLIDE 43

ForkJoinExample– Fibonacci

ForkJoinPoolpool=newForkJoinPool(); Fibonaccir=newFibonacci(10); pool.submit(r); while(!r.isDone()){ //Dosomework

42

42

//Dosomework ... } System.out.println("Resultoffib(10)=" +r.get());

slide-44
SLIDE 44

ForkJoinPerformanceDiscussion

  • Choosingthesequentialthreshold

− Smallertasksincreaseparallelism − Largertasksreducecoordinationoverhead − Ultimatelyyoumustprofileyourcode

  • Minimizesoverheadforcompute-intensivetasks

43

43

  • Minimizesoverheadforcompute-intensivetasks

− NotrecommendedfortasksthatmixCPUandI/Oactivity

  • Aportablewaytoexpressmanyparallelalgorithms

− Reasonablyefficientforawiderangeofcorecounts − Library-managedparallelism

slide-45
SLIDE 45

ClientLibraries

  • NimbusLookandFeel
  • PlatformAPIsforshapedandtranslucentwindows
  • JLayer(formerlyfromSwinglabs)
  • Optimized2Drendering

44

44

  • Optimized2Drendering
slide-46
SLIDE 46

NimbusLookandFeel

  • BetterthanMetalforcrossplatformlook-and-feel
  • IntroducedinJavaSE6u10,nowpartofSwing
  • NotthedefaultL&F

45

45

slide-47
SLIDE 47

JLayercomponent

EasyenrichmentforSwingcomponents

46

46

slide-48
SLIDE 48

JLayercomponent

Theuniversaldecorator

  • TransparentdecoratorforaSwingcomponent
  • Controlsthepaintingofitssubcomponents
  • Catchesallinputandfocuseventsforthewholehierarchy

//wrapyourcomponentwithJLayer JLayer<JPanel>layer =newJLayer<JPanel>(panel);

47

47

JLayer<JPanel>layer =newJLayer<JPanel>(panel); //customuiprovidesallextrafunctionality layer.setUI(myLayerUI); //addthelayerasusualcomponent frame.add(layer);

slide-49
SLIDE 49

TheDaVinciMachineProject(JSR-292)

(Amulti-languagerenaissancefortheJVM)

48

48

Better

slide-50
SLIDE 50

LanguagesLikeVirtualMachines

  • Programminglanguagesneedruntimesupport

− Memorymanagement/Garbagecollection − Concurrencycontrol − Security Reflection

49

49

− Reflection − Debuggingintegration − Standardlibraries

  • Compilerwritershavetobuildthesefromscratch
  • TargetingaVMallowsreuseofinfrastructure
slide-51
SLIDE 51

JVMSpecification

“TheJava virtualmachineknows nothingabouttheJava programminglanguage,onlyofa

50

50

particularbinaryformat,theclass fileformat.”

1.2TheJavaVirtualMachineSpec.

slide-52
SLIDE 52

LanguagesRunningontheJVM

Groovy JRuby … …

51

51

… Scala Clojure

slide-53
SLIDE 53

InvokeDynamicBytecode

  • JVMcurrentlyhasfourwaystoinvokemethod

− Invokevirtual,invokeinterface,invokestatic,invokespecial

  • Allrequirefullmethodsignaturedata
  • InvokeDynamicwillusemethodhandle

− Effectivelyanindirectpointertothemethod

52

52

  • Whendynamicmethodisfirstcalledbootstrapcode

determinesmethodandcreateshandle

  • Subsequentcallssimplyreferencedefinedhandle
  • Typechangesforceare-computeofthemethod

locationandanupdatetothehandle

− Methodcallchangesareinvisibletocallingcode

slide-54
SLIDE 54

CallSite andMethodHandle

  • invokedynamic linkedtoaCallSite

– CallSite canbelinkedorunlinked – CallSite holderofMethodHandle

  • MethodHandle isadirectlyexecutablereferenceto

anunderlyingmethod,constructor,field

– Cantransformargumentsandreturntype Transformation– conversion,insertion,deletion,substitution

53

53

– Transformation– conversion,insertion,deletion,substitution

slide-55
SLIDE 55

invokedynamic Step1-to-4

this[method_name](x,y)

invokedynamic [#bootstrapMethod] .this_method_name

classLanguageRuntime{ bootstrapMethod(info){ ... 1.Invokebootstrap 2.Produces CallSite 3.Completelinkage

54

54

... returnnewCallSite(); } classAClass{ aMethod(x,y){ ... } CallSite Method Handle 3.Completelinkage 4.Invokesmethod implementation

slide-56
SLIDE 56

MiscellaneousThings

  • Security
  • Ellipticcurvecryptography
  • TLS1.2
  • JAXP1.4.4
  • JAX-WS2.2

55

55

  • JAX-WS2.2
  • JAXB2.2
  • ClassLoaderarchitecturechanges
  • close() forURLClassLoader
  • JavadocsupportforCSS
slide-57
SLIDE 57

JDK7PlatformSupport

  • Windowsx86

− Server2008,Server2008R2,7&8(whenitGAs) − WindowsVista,XP

  • Linuxx86

− OracleLinux5.5+,6.x − RedHatEnterpriseLinux5.5+,6.x − SuSE LinuxEnterpriseServer10.x,11.x Ubuntu Linux10.04LTS,11.04

56

56

− Ubuntu Linux10.04LTS,11.04

  • Solarisx86/SPARC

− Solaris10.9+,11.x

  • AppleOSXx86

− Willbesupportedpost-GA,detailedplanTBD Note:JDK7shouldrunonprettymuchanyWindows/Linux/Solaris. TheseconfigurationsaretheonesprimarilytestedbyOracle,andfor whichweprovidecommercialsupport.

slide-58
SLIDE 58

JVMConvergence– Forwardlooking

Project“HotRockit”

  • Hotspot 21
  • JavaSE7Support
  • Rebranding
  • Improved JMX

Agent

  • Commandline

servicabilitytool

JDK7GA– 07/11

  • Hotspot 22
  • Performance
  • Enablelargeheaps

withreasonable latencies

JDK7u2

  • Hotspot 23
  • More performance
  • Improvedcommand

lineservicability (jcmd)

  • Enablelargeheaps

withconsistent reasonablelatencies

JDK7uX

  • Hotspot24
  • JavaSE8Support
  • Allperformance

featuresfrom JRockitported

  • Allservicability

featuresfrom JRockitported

JDK8GA

servicabilitytool (jrcmd)

  • -- Premium---
  • Improved JRockit

MissionControl Consolesupport reasonablelatencies

  • NoPermGen
  • -- Premium---
  • CompleteJRockit

FlightRecorder Support JRockitported

  • Compilercontrols
  • Verboselogging
  • -- Premium---
  • JRockitMission

ControlMemleak ToolSupport

  • SoftRealTimeGC
slide-59
SLIDE 59

ProjectLambda(JSR335)

Closuresandlambdaexpressions

ProjectJigsaw(JSR-294)

ModularizingtheJavaPlatform

JavaSE8

58

58

MoreProjectCoin

SmallLanguageChanges Closuresandlambdaexpressions Bettersupportformulti-coreprocessors

slide-60
SLIDE 60

Zusammenfassung

  • JavaSE7
  • Incrementalchanges
  • Evolutionary,notrevolutionary
  • Goodsolidsetoffeaturestomakedeveloperslifeeasier
  • JavaSE8

59

59

  • JavaSE8
  • Majornewfeatures:ModularisationandClosures
  • Moresmallerfeaturestobedefined
  • JavacontinuestogrowandadapttothechangingworldofIT
slide-61
SLIDE 61

VielenDankfürIhreAufmerksamkeit!

Wolfgang.Weigend@oracle.com

60

60

slide-62
SLIDE 62

61

61

slide-63
SLIDE 63

WirdJava7eingesetzt?

Umfrage aufjava.net:“HaveyoutriedoutJava7yet?”

Yes, and I`m working with it regulary (25%) I`ve experimented with it a bit (21%)

62

62

I plan to get started with Java 7 soon (25%) I`m waiting for a bug fix release (18%) No, and I don´t plan to (11%)

slide-64
SLIDE 64

JDK7UpdateReleases

Fehlerbereinigung

  • ProjektentwickeltUpdatesfürJDK7
  • SponsoristdieBuildGroup
  • MailingListelautetjdk7u-dev
  • TechnischeDiskussionzumJDK7UpdatesProjekt
  • ArchivevorhandenfürJuly2011,August2011

63

63

  • ArchivevorhandenfürJuly2011,August2011
  • NachrichtenanalleTeilnehmerverschicken:

jdk7u-dev@openjdk.java.net

  • jdk7u-devSubscription
  • JavaSE7Update2BinarySnapshotReleases
  • ListederÄnderungenimaktuellenJDK7u2Buildb02
  • ProjectFeedbackForumfürJavaSESnapshots
  • ReportaBugoderRequestaFeature
slide-65
SLIDE 65

OracleJavaMagazine

  • OnlineInformationenfürJavaTechnologie
  • ZusammenarbeitmitdergesamtenJavaCommunity
  • Oracle'sInvestmentzurStärkungvomJavaTechnologieÖkosystem

64

64