NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

  • 263 views
Uploaded on

New features in JavaSE 8. A short introduction.

New features in JavaSE 8. A short introduction.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
263
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
9
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Lee Chuk MunnLee Chuk Munn isslcm@nus.edu.sgisslcm@nus.edu.sg What's New inWhat's New in JavaSE 8?JavaSE 8?
  • 2. JavaSE TimelineJavaSE Timeline JDK 1.0 Jan 1996 JDK 1.1 Feb 1997 JDK 1.2 Dec 1998 JDK 1.3 May 2000 JDK 1.4 Dec 2002 JDK 5 Sept 2004 JDK 6 Dec 2006 JDK 7 July 2011 JDK 8 Mar 2014 5 years!
  • 3. What Happened?What Happened? ● Very ambitious – Modularity ● Refactor the JDK ● Native packaging – Lambda ● Language and libraries ● Lots of competing design – New bytecode to support dynamic languages – Lots of other proposed features ● Too many moving parts
  • 4. Java SE 7/SE 8Java SE 7/SE 8 ● Oracle acquired Sun in 2010 ● JavaSE 7 gestation period was too long – Developers are loosing interest ● Parts of the JDK was done, some was not – Eg invokedynamic was quite solid, closures were not ● Took a poll – Deliver it in 2 parts and what is completed sooner – Or wait for everything to complete – longer
  • 5. JavaSE 7JavaSE 7 ● Released on July 28 2011 ● Features – Project Coin – small change ● Integer literals, Strings in switch, type inferencing <> ● Multi-catch/precise rethrow ● Try-with-resources – NIO2 ● Paths, filesystem support, file attributes and permissions ● Async I/O, file system walker, filesystem watcher – Fork/join framework – invokedynamic
  • 6. Modernizing the Java PlatformModernizing the Java Platform ● Biggest change on the Java platform since JavaSE 5 – Change the way we write Java applications ● Language – Lambda expressions – Interface evolution ● Libraries – Bulk data operations on Collections ● Platform – Profiles
  • 7. LambdaLambda
  • 8. Computing TodayComputing Today ● Multicore is now the default ● Need to make writing parallel code easier ● Need to make libraries smarter – Utilize the cores
  • 9. Concurrency in JavaConcurrency in Java ● JDK 1.x – java.lang.Thread ● JDK 1.5 – java.util.concurrent – Locks, semaphores, Atomics – Callables – Synchronization data structures – cyclic barrier, count down latches, etc ● JDK 1.7 – Fork/join framework
  • 10. What's the IssueWhat's the Issue ● Preference for doing things in libraries vs doing things in the language ● Decent job of providing easy to use parallel libraries ● Need to reduce conceptual and syntactic gap between serial and parallel – Serial and parallel code for a given task looks very different ● Need language changes to better support the libaries
  • 11. Student with the Highest ScoreStudent with the Highest Score Collection<Student> students = … double highestScore = 0.0; for (Student s : students) if ((s.gradYear == 2013) && (s.score > highestScore)) highestScore = s.score;
  • 12. Student with the Highest ScoreStudent with the Highest Score Collection<Student> students = ... double highestScore = 0.0; for (Student s : students) { if ((s.gradYear == 2013) && (s.score > highestScore)) highestScore = s.score; } ● Code is inherently serial – Iterate through students serially – Stateful – use of highestScore ● Client determines how to iterate the collection – Not the collection
  • 13. Using Functional Language StyleUsing Functional Language Style HypotheticalCollection student = … double highestScore = student .filter(new Predicate<Student>() { public boolean op(Student s) { return (s.getGraduateYear() == 2013); } }) .map(new Mapper<Student, Double>() { public double extract(Student s) { return (s.getScore()); } }) .max(); Stateless functions and immutable data But syntactically ugly !!!
  • 14. What is Closure?What is Closure? function adder(x) { return (function(y) { return (x + y); }); } var addTo3 = adder(3); Var addTo7 = adder(7); console.log(addTo3(5) + addTo7(5)); → 21 A function together with a referencing environment for the non local (free variable) variables of the function. Once defined, the free variables are bound to the function, or “closes over” it.
  • 15. Lambda Expressions in JavaLambda Expressions in Java ● Lambda expressions are anonymous functions – Like a method, has a typed argument list, a return type, a set of thrown exceptions, a body – Body can be an expression or a block double highestScore = students .filter((Student s) -> s.getGradYear() == 2013) .map((Student s) -> s.getScore()) .max();
  • 16. Lambda TypesLambda Types ● SAM – Single Abstract Method – Annotated with @FunctionalInterface ● Not necessary, like @Override – Ensures that the functional interface contract is honoured .map((Student s) -> s.getScore()) What is this type?
  • 17. ExampleExample File srcDir = new File(“/home/cmlee/src”); for (File f: srcDir.listFiles( (File sf) -> sf.getName().endsWith(“.java”)) //Do something with f FileFilter.accept(File f) returns boolen
  • 18. Target TypingTarget Typing File srcDir = new File(“/home/cmlee/src”); for (File f: srcDir.listFiles( (File sf) -> sf.getName().endsWith(“.java”)) //Do something with f FileFilter.accept(File f) returns boolen File srcDir = new File(“/home/cmlee/src”); for (File f: srcDir.listFiles( sf -> sf.getName().endsWith(“.java”)) //Do something with f Simplified to Target typing – inferring the Lambda expression type
  • 19. Target TypingTarget Typing ● Same lambda expression can be assigned to different SAM FileFilter fileFilter = f -> f.getName().endsWith(“.java”); DirectoryStream.Filter<File> directoryFilter = f -> f.getName().endsWith(“.java”); Lambda literal
  • 20. Method ReferenceMethod Reference ● Reuse a method as a Lambda expression – Does not have to be static – Use :: to reference it File srcDir = new File(“/home/cmlee/src”); for (File f: srcDir.listFiles(File::canRead) { //Do something with f
  • 21. DefaultDefault MethodsMethods
  • 22. InterfacesInterfaces ● Methods in interfaces are cast in stone – If you do, you break backward compatibility – Classes need to be recompiled ● If you cannot change an interface you cannot refactor ● Issue with evolving libraries that are based on interfaces – Eg java.util.List, java.util.ListEx, java.util.ListEx2
  • 23. Default MethodsDefault Methods ● New methods with default implementation to existing interfaces – Without recompiling the implementation class ● New implementation can decide if they want to reimplement the default methods – “Mirandarizing” the implementation package java.util; public interface List<T> { //Existing methods... ... default public void sort(Comparator<? super T> cmp) { //Sort the list ... } }
  • 24. Benefits of Default MethodsBenefits of Default Methods ● Retrofitting existing API with newer capabilities – Enumeration have been superseded by Iterator interface Enumeration<E> extends Iterator<E> { //Existing Enumeration methods boolean hasMoreElements(); E nextElement(); //Methods from Iterator default boolean hasNext() { return (hasMoreElements()); } default E next() { return (nextElement()); } default void remove() { throw new UnsupportedOperationException(); } }
  • 25. StreamsStreams
  • 26. CollectionsCollections ● Collections are data structure – List, Set, Queue, Stack – Size of data is fixed at the point of using it ● Operations on collections can potentially mutate the state of the collection – Not thread friendly – Eg. remove() ● Values cannot be lazily generated – How do you represent and random set of positive numbers?
  • 27. What are Streams?What are Streams? ● Conduit for data flow ● As the data are flowing, perform operation on them ● Streams are composable – Combine one stream with anohter ● Does not modify the source
  • 28. Creating StreamsCreating Streams ● Explicitly ● From collections ● From suppliers/generators Stream.of(new int[] {0, 1, 2, 3, 4, 5, 6}); List<Integer> intList = new LinkedList<>(); //Initialize int list ... intList.stream(); final Random rand = new Random(); Stream.of(()-> rand.nextInt()); IntStream.generate(() → rand.nextInt())... LongStream.range(0, 1000L)...
  • 29. Streams ExampleStreams Example Set<Student> students = … for (Student s: students) System.out.println(“Name: %s, Email: %s” , s.getName(), s.getEmail()); students.stream().forEach(s -> { System.out.println(“Name: %s, Email: %s” , s.getName(), s.getEmail()); }); Refactor to
  • 30. Streams ExampleStreams Example Set<Student> students = … students.stream() .filter(s -> (2013 == s.getGradYear()) && (s.getScore() > 90)) .findAny() //Returns Optional .ifPresent(s -> { System.out.println(s); }) Print out the names of all honor students for 2013 LINQ like DSL
  • 31. JavaScriptJavaScript (and dynamic language support)(and dynamic language support)
  • 32. Dynamic Language SupportDynamic Language Support ● http://www.is- research.de/info/vmlanguages/category/jvm-language/ – Some are academic, experimentation – You can find a Java implementation form MOST dynamic/scripting languages – prefix with j ● JavaScript, Lua, Python, Haskell, Scheme,... – Some are JVM specific ● Scala, Groovy, Clojure – Some in serious use ● Scala, JRuby, Groovy, Clojure
  • 33. Java Virtual MachineJava Virtual Machine ● Reasons for targeting the JVM – Java language != Java Virtual Machine – Mature, performant, scalable, introspection, ubiquitous ● Dynamic language support began in JDK 6 ● Integration with Java ecosystem – Large set of libraries ● Use cases – Java calling into script – adding scripting capabilities to Java application – Script calling into Java – prototyping
  • 34. DemoDemo
  • 35. Scripting ExampleScripting Example config.js ScriptEngine jsEngine = mgr.getEngineByName(“JavaScript”); //Application configuration bean MyAppConfig appConfig = new MyAppConfig(); //Bind appConfig to config jsEngine.put(“config”, appConfig); jsEngine.eval(new FileReader(“confing.js”)); config.server = “myserver” config.port = 12345 //Dynamically determine timeout config.timeout = calculateTimeout()
  • 36. JavaScriptJavaScript this[method_name](x, y); How do you generate the byte code for the call?
  • 37. invokedynamicinvokedynamic this[method_name](x, y) invokedynamic [#bootstrapMethod] .this_method_name class LangaugeRuntime { bootstrapMethod(info) { ... return new CallSite(); } class AClass { aMethod(x, y) { ... } CallSite Method Handle 1. Invoke bootstrap 2. Produces CallSite 3.Complete linkage 4. Invokes method implementation
  • 38. NashornNashorn ● A new Javascript engine based on invokedynamic – To supercede Rhino in JavaSE 8 ● Why? – Node.js on Java? - https://avatar-js.java.net – Javascript container ala PhoneGap/Cordova, Adobe AIR ● Side note: javafx.scene.web.WebView – Wrapper for WebKit – Now you can display HTML pages (with JavaScript) correctly in Java
  • 39. ProfilesProfiles
  • 40. The Java RuntimeThe Java Runtime ● The JDK is big and monolithic – Lots of improvement over the years: warm start, memory images ● Slow startup time, memory footprint – Why should the VM load javax.swing.Jframe when you are just using classes from java.lang package? ● Single codebase – simplify engineering, better code quality – From small to big – Not the case: CLDC, CDC, JavaSE ● Versioning?
  • 41. Compact ProfilesCompact Profiles ● A step toward full modularization – Coming in JavaSE 9 (I hope) ● Enable applications that use only a subset of the JavaSE platform on resource constrained devices – Eg. CLDC, CDC ● Profiles – The entire JVM and the JLS spec – Define a subset of the API – Larger profiles must be superset of smaller ones – The contents of the API packages must be the same as the full SE platform
  • 42. Compact ProfilesCompact Profiles ● compact1 – 14MB – Smallest set of API packages – 14MB – java.lang, java.nio, java.util, java.net, java.security ● compact2 – 18MB – compact1 + XML + RMI + JDBC ● compact3 – 21MB – compact2 + everything except Desktop, JAX-WS/JAXB, CORBA ● Full SE – 45MB ● See https://blogs.oracle.com/jtc/entry/a_first_look_at_compact
  • 43. Good Use Cases?Good Use Cases? Linux X86 Linux ARM soft float Linux ARM VFP soft float Linux ARM VFP hard float Linux PowerPC Linux PowerPC e500v2
  • 44. Compact Profile ToolsCompact Profile Tools ● Restricting compiles to a profile ● Analyzing compact dependency $ jdeps -P Hello.class Hello.class -> /opt/java/jdk1.8.0/jre/lib/rt.jar (compact1) <unnamed> (Hello.class) -> java.io compact1 -> java.lang compact1 $ javac -profile compact1 Hello.class
  • 45. Use The Docs Luke...Use The Docs Luke...
  • 46. Embedded JavaEmbedded Java ● Can be downloaded from Oracle website ● Commercial product Prebuild profiles ejdk1.8.0 ejdk1.8.0/{architecture} ejdk1.8.0/{architecture}/compact1 ejdk1.8.0/{architecture}/compact2 ejdk1.8.0/{architecture}/compact3 ejdk1.8.0/{architecture}/jre ejdk1.8.0/{architecture}/extensions Custom profiles ejdk1.8.0/bin/jrecreate.sh
  • 47. MiscellaneousMiscellaneous
  • 48. Parameter NamesParameter Names ● Reflection now returns parameter names ● Good news for all tools and framework developers ● Hypothetical example from JAX-RS @GET @Path(“{custId}”) public void get(@PathParam(“custId”) int custId) { ... @GET @Path(“{custId}”) public void get(@PathParam int custId) { ...
  • 49. AnnotationAnnotation ● Annotations are pieces of information embedded in the class files – Typically used by tools to generate code, enforce certain programming practices, etc ● Processed during – Compile time – At runtime ● You can annotate – Package, class, member, constructor, method, parameters, local variable, annotation
  • 50. Type AnnotationType Annotation ● Annotations can currently be used on type declarations – Package, class, member, constructor, method, parameters, local variable, annotation ● Annotations can now be used on where types are used – Permits error detection by pluggable type checkers – See http://types.cs.washington.edu/checker-framework List<@Email String> emails = new @ReadOnly LinkedList<String>(aCollection); if ((@NonNull)obj) instanceof String)
  • 51. Date TimeDate Time LocalDate yesterday = LocalDate.now().minusDays(1); ZoneId.getAvailableZoneIds().stream() .forEach(tz -> { System.out.println(tz); });