Lucky Seven
Neuerungen in Java 7
Wolfgang Weigend
Oracle Deutschland B.V. & Co. KG
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
Neuerungen in Java 7
Oracle Deutschland B.V. & Co. KG
<InsertPictureHere>
NeuerungeninJava7 Diewichtigsten Änderungen,Erweiterungen
P
SystemberaterJavaTechnologieundArchitektur
PrioritiesfortheJavaPlatforms
GrowDeveloperBase GrowAdoption IncreaseCompetitiveness IncreaseCompetitiveness Adapttochange
JavaCommunities
HowJavaEvolvesandAdapts
CommunityDevelopmentof JavaTechnologySpecifications
JCPReforms
EvolvingtheLanguage
From“EvolvingtheJavaLanguage” - JavaOne2005
– Readingismoreimportantthanwriting – Codeshouldbeajoytoread – Thelanguageshouldnothidewhatishappening – Codeshoulddowhatitseemstodo – Simplicitymatters – Every“good” featureaddsmore“bad” weight 6
6
– Every“good” featureaddsmore“bad” weight – Sometimesitisbesttoleavethingsout
Soyouwanttochangethelanguage?
7
7
JavaSE7ReleaseContents
8
8
<InsertPictureHere>
Section Divider
9
9
ProjectCoinConstraints
Coordinatewithlargerlanguagechanges
10
10
– ProjectLambda – Modularity
BetterIntegerLiteral
intmask=0b101010101010;
11
11
intmask=0b1010_1010_1010; longbig=9_223_783_036_967_937L;
StringSwitchStatement
enumconstants
12
12
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)) ...
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: ...
SimplifyingGenerics
ListstrList=newArrayList();
15
15
SimplifyingGenerics
ListstrList=newArrayList();
List<String> strList=newArrayList<String>();
16
16
List<String> strList=newArrayList<String>();
SimplifyingGenerics
ListstrList=newArrayList();
List<String> strList=newArrayList<String>();
17
17
List<String> strList=newArrayList<String>(); List<Map<String,List<String>> strList= newArrayList<Map<String,List<String>>();
DiamondOperator
ListstrList=newArrayList();
List<String> strList=newArrayList<String>();
18
18
List<Map<String,List<String>> strList= newArrayList<Map<String,List<String>>(); List<String> strList=newArrayList<>(); List<Map<String,List<String>> strList= newArrayList<>();
CopyingaFile
InputStreamin=newFileInputStream(src); OutputStreamout=newFileOutputStream(dest); byte[]buf=newbyte[8192]; intn;
19
19
while(n=in.read(buf))>=0)
CopyingaFile(Better,butwrong)
InputStreamin=newFileInputStream(src); OutputStreamout=newFileOutputStream(dest); try{ byte[]buf=newbyte[8192];
20
20
intn; while(n=in.read(buf))>=0)
}finally{ in.close();
}
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)
}finally{
} }finally{ in.close(); }
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)
}finally{
} }finally{ in.close(); }
Exceptionthrownfrom potentiallythreeplaces. Detailsoffirsttwocouldbelost
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)
}
TheDetails
finallyblockswithvariablestotrackexceptionstate
usinganewfacilityofThrowable
24
24
useablewithtry-with-resources
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)
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
HeapPollution– JLSv34.12.2.1
thatisnotofthatparameterizedtype
mightpointtoanarrayofListswheretheListsdid notcontainstrings
27
27
notcontainstrings
atruntime
VarargsWarningsRevised
methoddeclarations
warningsatthedeclarationandcallsites canbe suppressed
28
28
suppressed
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; }
Multi-Catch
try{ ... }catch(ClassCastExceptione){ doSomethingClever(e); throwe; }catch(InstantiationException|
30
30
NoSuchMethodException| InvocationTargetExceptione){ log(e); throwe; }
IDESupport
31
31
32
32
NewI/O2(NIO2)Libraries
JSR203
33
33
JavaNIO2Features
− Biggestimpactondevelopers
− Staticmethodstooperateonfilesanddirectories Supportforsymboliclinks
34
34
− Supportforsymboliclinks
− Representsunderlyingfilestorage(partition,concretefilesystem)
− SPIinterfacetoafilesystem(FAT,ZFS,Ziparchive,network,etc)
Path Class
– Immutable
− 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();
FileOperation– Copy,Move
– 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
– 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);
Directories
– Scalestolargedirectories – Useslessresources – Smoothoutresponsetimeforremotefilesystems – ImplementsIterable andCloseable forproductivity
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()); }
ConcurrencyAPIs
− UpdatetoJSR166xwhichwasanupdatetoJSR166
− AlsoreferredtoasFork/Join
38
− BarriersimilartoCyclicBarrier andCountDownLatch
− ExtensiontoBlockingQueue − ImplementedbyLinkedTransferQueue
ForkJoinFramework
smallerpieces
– Eg.Fibonaccinumberfib(10)=fib(9)+fib(8)
join fork 39
39
ifIcanmanagethetask performthetask else forktaskintox numberofsmaller/similartask jointheresults
join fork
KeyClasses
– ExecutorserviceforrunningForkJoinTask
– Thebaseclassforforkjointask
– AsubclassofForkJoinTask Arecursiveresultlesstask
40
40
– Arecursiveresultlesstask – Implementscompute() abstractmethodtoperformcalculation
– SimilartoRecursiveAction butreturnsaresult
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()); } } }
ForkJoinExample– Fibonacci
ForkJoinPoolpool=newForkJoinPool(); Fibonaccir=newFibonacci(10); pool.submit(r); while(!r.isDone()){ //Dosomework
42
42
//Dosomework ... } System.out.println("Resultoffib(10)=" +r.get());
ForkJoinPerformanceDiscussion
− Smallertasksincreaseparallelism − Largertasksreducecoordinationoverhead − Ultimatelyyoumustprofileyourcode
43
43
− NotrecommendedfortasksthatmixCPUandI/Oactivity
− Reasonablyefficientforawiderangeofcorecounts − Library-managedparallelism
ClientLibraries
44
44
NimbusLookandFeel
45
45
JLayercomponent
EasyenrichmentforSwingcomponents
46
46
JLayercomponent
Theuniversaldecorator
//wrapyourcomponentwithJLayer JLayer<JPanel>layer =newJLayer<JPanel>(panel);
47
47
JLayer<JPanel>layer =newJLayer<JPanel>(panel); //customuiprovidesallextrafunctionality layer.setUI(myLayerUI); //addthelayerasusualcomponent frame.add(layer);
TheDaVinciMachineProject(JSR-292)
(Amulti-languagerenaissancefortheJVM)
48
48
Better
LanguagesLikeVirtualMachines
− Memorymanagement/Garbagecollection − Concurrencycontrol − Security Reflection
49
49
− Reflection − Debuggingintegration − Standardlibraries
JVMSpecification
“TheJava virtualmachineknows nothingabouttheJava programminglanguage,onlyofa
50
50
particularbinaryformat,theclass fileformat.”
1.2TheJavaVirtualMachineSpec.
LanguagesRunningontheJVM
Groovy JRuby … …
51
51
… Scala Clojure
InvokeDynamicBytecode
− Invokevirtual,invokeinterface,invokestatic,invokespecial
− Effectivelyanindirectpointertothemethod
52
52
determinesmethodandcreateshandle
locationandanupdatetothehandle
− Methodcallchangesareinvisibletocallingcode
CallSite andMethodHandle
– CallSite canbelinkedorunlinked – CallSite holderofMethodHandle
anunderlyingmethod,constructor,field
– Cantransformargumentsandreturntype Transformation– conversion,insertion,deletion,substitution
53
53
– Transformation– conversion,insertion,deletion,substitution
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
MiscellaneousThings
55
55
JDK7PlatformSupport
− Server2008,Server2008R2,7&8(whenitGAs) − WindowsVista,XP
− 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
− Solaris10.9+,11.x
− Willbesupportedpost-GA,detailedplanTBD Note:JDK7shouldrunonprettymuchanyWindows/Linux/Solaris. TheseconfigurationsaretheonesprimarilytestedbyOracle,andfor whichweprovidecommercialsupport.
JVMConvergence– Forwardlooking
Project“HotRockit”
Agent
servicabilitytool
JDK7GA– 07/11
withreasonable latencies
JDK7u2
lineservicability (jcmd)
withconsistent reasonablelatencies
JDK7uX
featuresfrom JRockitported
featuresfrom JRockitported
JDK8GA
servicabilitytool (jrcmd)
MissionControl Consolesupport reasonablelatencies
FlightRecorder Support JRockitported
ControlMemleak ToolSupport
ProjectLambda(JSR335)
Closuresandlambdaexpressions
ProjectJigsaw(JSR-294)
ModularizingtheJavaPlatform
JavaSE8
58
58
MoreProjectCoin
SmallLanguageChanges Closuresandlambdaexpressions Bettersupportformulti-coreprocessors
Zusammenfassung
59
59
VielenDankfürIhreAufmerksamkeit!
Wolfgang.Weigend@oracle.com
60
60
61
61
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%)
JDK7UpdateReleases
Fehlerbereinigung
63
63
jdk7u-dev@openjdk.java.net
OracleJavaMagazine
64
64