Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov


Published on

Java 7 - New Features
Introduction and Chronology
Compressed 64-bit Object Pointers
Garbage-First GC (G1)
Dynamic Languages in JVM
Java Modularity – Project Jigsaw
Language Enhancements (Project Coin)
Strings in Switch
Automatic Resource Management (ARM)
Improved Type Inference for Generic Instance Creation
Improved Type Inference for Generic Instance Creation
Simplified Varargs Method Invocation
Collection Literals
Indexing Access Syntax for Lists and Maps
Language Support for JSR 292
Underscores in Numbers
Binary Literals
Closures for Java
First-class Functions
Function Types
Lambda Expressions
Project Lambda
Extension Methods
Upgrade Class-Loader Architecture
Method to close a URLClassLoader
Unicode 5.1
JSR 203: NIO.2
SCTP (Stream Control Transmission Protocol)
SDP (Sockets Direct Protocol)

Published in: Technology
1 Comment
  • Nice and Useful Presentation
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov

  1. 1. Java 7 – New Features<br />Mihail Stoynov, Svetlin Nakov<br />Bulgarian Association of Software Developers<br />Spring Conference of the Bulgarian Oracle User Group (BGOUG), Plovdiv, 24 April 2010<br /><br />
  2. 2. Table of Contents<br />Introduction and Chronology<br />Compressed 64-bit Object Pointers<br />Garbage-First GC (G1)<br />Dynamic Languages in JVM<br />Java Modularity –Project Jigsaw<br />Language Enhancements (Project Coin)<br />Strings in Switch<br />Automatic Resource Management (ARM)<br />Improved Type Inference for Generic Instance Creation<br />
  3. 3. Table of Contents (2)<br />Improved Type Inference for Generic Instance Creation<br />Simplified Varargs Method Invocation<br />Collection Literals<br />Indexing Access Syntax for Lists and Maps<br />Language Support for JSR 292<br />Underscores in Numbers<br />Binary Literals<br />Closures for Java<br /> First-class Functions<br />
  4. 4. Table of Contents (3)<br /> Function Types<br /> Lambda Expressions<br /> Project Lambda<br /> Extension Methods<br />Upgrade Class-Loader Architecture<br />Method to close a URLClassLoader<br />Unicode 5.1<br />JSR 203: NIO.2<br />SCTP (Stream Control Transmission Protocol)<br />SDP (Sockets Direct Protocol)<br />
  5. 5. Introduction and Chronology<br />
  6. 6. OpenJDK<br />JDK7 is the second JDK done via the OpenJDK effort<br />OpenJDK is free, open-source and GPL licensed<br />A lot of the improvements of JDK7 are separate projects on OpenJDK<br />Some say that projects go under the cap of OpenJDK to avoid the cumbersome and slow JCP process<br />
  7. 7. Milestones<br />Began in August 2006<br />First supposed to be 7 milestones<br />Mark Reinhold extended them to 10<br />Current status: M7 finished, presentation made with build89<br />M10 expected to finish 09.09.2010<br />“The last scheduled milestone cycle will be followed by a test and stabilization period of indeterminate length, after which the final release will be declared”<br />
  8. 8. There’s No JSR Yet<br />A JSR is supposed to be formed<br />Java SE 6 was under the 'Umbrella' JSR 270<br />JDK7 is in Eclipse’s low priority list because a lack of container JSR<br />JDK7 cannot be finalized without a JSR<br />There are some functionalities that also lack a JSR<br />While doing this presentation we used the term JSR TBD in lieu of the missing JSR<br />
  9. 9. Source Control System<br />Official SCM is SVN, still<br />Note: it takes a 'while'<br />Unofficial Mercurial forest repositories available since November 2007<br />Note: this also takes a 'while'<br />>svn co<br />>hg fclone<br />
  10. 10. Currently Supported IDEs<br />Eclipse<br />Both Eclipse 3.6M6 and E4 do not support JDK7’s syntax<br />…or the presenters couldn’t figure it out <br />Strangely enough the option is there:<br />Source compatibility: 1.7<br />NetBeans<br />6.9 Beta supports JDK7<br />All the demos are done with it<br />Eclipse was used to create the presentation <br />
  11. 11. Compressed 64-bit Object Pointers<br />
  12. 12. What is an oop?<br />An "oop", or "ordinary object pointer" in HotSpot parlance is a managed pointer to an object<br />it is normally the same size as a native machine pointer<br />which means 64 bits on an LP64 system<br />(LP64 = Long and Pointer are 64bit long)<br />On an ILP32 system, there is a maximum heap size of somewhat less than 4GB<br />which is not enough for many applications<br />
  13. 13. The Problem – 50% Larger Heap<br />On an LP64 system the heap for any given run may have to be around 1.5 times as large as for the corresponding IPL32 system <br />assuming the run fits both modes<br />This is due to the expanded size of managed pointers<br />Memory is pretty cheap, but these days bandwidth and cache is in short supply<br />so significantly increasing the size of the heap just to get over the 4GB limit is painful<br />
  14. 14. Compressed oops<br />Compressed oops = managed pointers<br />32-bit values, must be scaled by a factor of 8 and added to a 64-bit base address to find the object they refer to<br />in many but not all places in the JVM<br />This allows applications to address up to four billion objects (not bytes)<br />or a heap size of up to about 32Gb<br />At the same time, data structure compactness is competitive with ILP32 mode<br /><base> + (<narrow-oop> << 3) + <offset><br />
  15. 15. Encoding / Decoding<br />The term decode expresses the operation by which a 32-bit compressed oop is converted into a 64-bit native address into the heap<br />The inverse operation is encoding<br />All oops are the native machine word size in<br />An ILP32-mode JVM<br />In LP64 mode, when the UseCompressedOops flag is turned off<br />The Hotspot VM's data structures to manage Java classes are not compressed<br />
  16. 16. Null Processing<br />A 32-bit zero value decodes into a 64-bit native null value<br />An awkward special path is required in the decoding logic<br />It is profitable to statically note which compressed oops are guaranteed never to be null and use a simpler version of the full decode or encode operation<br />Implicit null checks are crucial to JVM speed<br />Trick: if compressed null is ever decoded, there’s a signal – the first page or so of the virtual addresses used by heap is not mapped<br />
  17. 17. Zero Based Compressed oops<br />Narrow oop base = java heap base minus one protected page (for implicit null checks)<br />If the narrow oop base can be made to be zero:<br />Also if Java heap size < 4Gb and it can be moved into low virtual address space (below 4Gb) then compressed oops can be used without encoding/decoding<br /><oop-base> + (<narrow-oop> << 3) + <field-offset><br />(<narrow-oop> << 3) + <field-offset><br /><wide_oop> = <narrow-oop><br />
  18. 18. Garbage-First GC (G1)<br />
  19. 19. Java GC – Introduction<br />Java GC divides heap into young and old generations of objects<br />Takes advantage of the observation that the vast majority of objects die young glorious deaths<br />Very small number of objects live for a very long time (effectively the life of the app)<br />Few references from the old generation to the young generation<br />Focus collection attention on the young gen<br />
  20. 20. Concurrent Mark Sweep GC<br />Garbage collector up to and including Java 6 is called Concurrent Mark Sweep (CMS)<br />CMS has minor and major cycles (for different gen spaces – young, tenured, perm)<br />Young gen GC is concurrent<br />Old gen GC does stop-the-world pauses to mark and finish up<br />Fallback to full stop-the-world for old gen compaction<br />
  21. 21. G1 Garbage Collector<br />G1 divides the all memory (except perm gen) into 1 MB “regions”<br />Regions are either old or young<br />In G1, the old generation GC there is one stop-the-world pause to mark<br />G1 uses “remembered sets” to manage references into a region<br />Every region has a small data structure (<5% of total heap)<br />The remembered sets contain all external references into that region<br />
  22. 22. G1 Additional Facts<br />Garbage-first is a server-style garbage collector<br />Targeted for multi-processors with large memories<br />meets a soft real-time goal with high probability<br />while achieving high throughput<br />Added in Milestone1 (02.01.2009)<br />Released in Java 6 update 6u14<br />Support contract controversy<br />
  23. 23. Dynamic Languages in JVM<br />
  24. 24. Dynamic Languages in JVM<br />Da Vinci Machine Project<br />A.k.a. Multi Language Virtual Machine –<br />Aimed to allow non-Java languages to run efficiently in the JVM<br />JSR 292: Supporting Dynamically Typed Languages on the Java Platform<br />The standard behind Da Vinci Machine<br />Natural continuation of JSR 223: Scripting for the Java Platform implemented in JDK 6<br />
  25. 25. Dynamic Languages in JVM (2)<br />New JVM instruction invokedynamic<br />Allows extremely fast dynamic method invocation through method handles<br />Will enable JRuby, Jython, Groovy and other dynamic and scripting languages to call dynamic methods natively at bytecode level<br />Method handles<br />Lightweight references to a method – java.dyn.MethodHandle<br />Anonymous classes in the JVM<br />
  26. 26. Dynamic Languages in JVM (3)<br />Autonomous methods<br />Methods that can be dynamically attached to an existing class at runtime<br />Interface injection<br />Acquiring base interfaces and method implementations at runtime<br />Continuations and stack introspection <br />Suspend / resume thread's execution stack<br />Tail calls and tail recursion <br />
  27. 27. Dynamic Languages in JVM (4)<br />Runtime support for closures<br />Closure is a lambda-expression bound (closed) to its environment<br />Multimethods<br />Dispatch a method overload depending on the actual arguments at runtime<br />Faster reflection and faster interface invocation based on dynamic invocation<br />Symbolic freedom for identifier names<br />
  28. 28. Dynamic Invoke – Example<br />staticvoid greeter(String x) {<br /> System.out.println("Hello, " + x);<br />}<br />static MethodHandle greeterMethodHandle =<br /> MethodHandles.lookup().findStatic(<br /> DynamicInvocation.class, "greeter", MethodType.<br /> methodType(void.class, String.class));<br />static {<br /> Linkage.registerBootstrapMethod(<br />"bootstrapDynamic");<br />}<br />
  29. 29. Dynamic Invoke – Example (2)<br />privatestatic CallSite bootstrapDynamic(<br /> Class caller, String name, MethodType type) {<br />if (type.parameterCount() == 1 && name == "hail") {<br /> MethodHandle target = MethodHandles.<br /> convertArguments(greeterMethodHandle, type);<br /> CallSite site = new CallSite(caller, name, type);<br /> site.setTarget(target);<br /> System.out.println("Set the CallSite target to " +<br /> greeterMethodHandle);<br />return site;<br /> }<br />}<br />publicstaticvoid main(String... args) {<br /> InvokeDynamic.hail("dynamic invocation");<br />}<br />
  30. 30. Java Modularity<br />Project Jigsaw<br />
  31. 31. Introduction<br />The JDK and the JRE, have always been delivered as massive, indivisible artifacts<br />The growth of the platform has thus inevitably led to the growth of the basic JRE download<br />which now stands at well over 14MB<br />despite heroic engineering efforts such as the Pack200 class file compression format<br />Java Kernel and Quickstarter features do improve download time and startup time, at least for Windows users<br />
  32. 32. The Real Solution<br />The most promising way to improve the key metrics of<br />Download time<br />Startup time<br />And memory footprint<br />Is to attack the root problem head-on:<br />Divide the JDK into a set of well specified and separate, yet interdependent, modules<br />A side effect is that JAR format has to reworked<br />
  33. 33. Alan Bateman: It’s Difficult<br />Suppose you are using the Logging API<br />Logging requires NIO (for file locking)<br />And JMX (as loggers are managed)<br />JMX requires JavaBeans, JNDI, RMI and CORBA (JMX remote API mandates that the RMI connector support both JRMP and IIOP)<br />JNDI requires java.applet.Applet (huh?) and JavaBeans has dependencies on AWT, Swing<br />Not satisfied with this, JavaBeans has persistent delegates that create dependencies on JDBC and more<br />
  34. 34. How to Do It?<br />Modularizing the JDK requires a module system capable of supporting such an effort <br />It requires, in particular, a module system whose core can be implemented directly within the Java virtual machine<br />Modularizing is best done with a module system that’s tightly integrated with the Java language<br />Otherwise the compile-time module environment can differ dramatically from the run-time module environment<br />
  35. 35. Which Module System?<br />JSR 277 proposes the JAM module system<br />Some of its rich, non-declarative features would be impossible to implement its core functionality directly within the JVM<br />Therefore Sun halted the development<br />JSR 294 is chartered to extend the language and JVM to support modular programming<br />Well received for its simplicity and its utility to existing module systems such as OSGi<br />
  36. 36. Which Module System? (2)<br />OSGi<br />May 2007: OSGi 4.1 standardized as JSR-291<br />Reasonably mature, stable, and robust<br />Implemented within Apache Harmony JVM<br />Not at all integrated with the Java language<br />Jigsaw created to modularize JDK7<br />Will not be an official part of the Java SE 7 Platform Specification and might not be supported by other SE 7 implementations<br />
  37. 37. Status and Examples<br />Probably JSR 294 will be chosen<br />There are issues, JSR 294 is inactive (paused)<br />Not implemented yet (b89), java.lang.module<br />Example (may, and probably will, change)<br />module M1@1.0 provides M2@2.0, M3@3.0 {<br />requires M4@4.0, M5@5.0;<br />permits M6; // only M6 can depend on M1<br />}<br />module M;<br />package P;<br />publicclassFoo {...}<br />
  38. 38. JSR 308: Annotations on Java Types<br />
  39. 39. JSR 308 – Introduction<br />Java SE 6 permits annotations only on declarations<br />JSR 308 extends Java’s annotation system so that annotations may appear on nearly any use of a type<br />JSR 308 is backward-compatible and continues to permit those annotations<br />Two new types of annotations (target wise):<br />ElementType.TYPE_USE<br />ElementType.TYPE_PARAMETER<br />
  40. 40. Source Locations for Annotations on Types<br /> A type annotation appears before the type<br />The annotation on a given array level prefixes the brackets that introduce that level<br />The varargs syntax ... is treated analogously to array brackets and may also be prefixed by an annotation<br />@Nonnull String s = "";<br />publicstaticvoid main(String @NonEmpty ... args) {<br />@English String s @NonEmpty [] = new String[]{""};<br />}<br />
  41. 41. Source Locations for Annotations on Types (2)<br />An annotation on the type of a method receiver (this) appears just after the parameter list and before any throws clause<br />Each non-static method has an implicit parameter, this, which is called the receiver<br />An annotation on a type parameter declaration appears before the declared name or wildcard<br />public String toString() @Readonly { ... }<br />Map<@NonNull String,<br />@NonEmpty List<@Readonly Document>> f;<br />
  42. 42. JSR 308: More Examples<br />publicstaticvoid main() {<br />//for generic type arguments in a generic method<br /> JSR308Example2.<@NonNull String>method("...");<br />//for type parameters and type parameter bounds:<br /> Collection<@Long ? super@Existing File> c = null;<br />//for class inheritance:<br /> class UnmodifiableList<T> implements<br />@Readonly List<@Readonly T> { }<br />}<br />//for throws clauses:<br />void monitorTemperature() throws@Critical Exception {}<br />//for method receivers:<br />public String toString() @Readonly { returnnull; }<br />// helper only<br />publicstatic <T> T method(String s) {returnnull;}<br />
  43. 43. Reflection<br />Type Annotations are available in b89<br />Introduced in M4<br />Unfortunately the specification says:<br />“To do: Complete this design.”<br />So Reflection API is not ready yet<br />Anyway reflection gives no access to method implementations<br />
  44. 44. Usage of Type Annotations<br />One example use is to create custom type qualifiers for Java<br />such as @NonNull, @ReadOnly, @Interned<br />A declaration that uses a qualified type provides extra information<br />A designer can define new type qualifiers using Java annotations, and can provide compiler plug-ins to check their semantics<br />For instance, by issuing lint-like warnings during compilation<br />Example Plug-in: The Checker Framework<br />
  45. 45. An Example That Makes Sense<br />@DefaultQualifier("NonNull")<br />class DAG {<br /> Set<Edge> edges;<br />// ...<br /> List<Vertex> getNeighbors(<br />@Interned @Readonly Vertex v) @Readonly {<br /> List<Vertex> neighbors = new LinkedList<Vertex>();<br />for (Edge e : edges)<br />if (e.from() == v)<br /> neighbors.add(;<br />return neighbors;<br /> }<br />}<br />
  46. 46. Small Language Enhancements (Project Coin)<br />
  47. 47. Project Coin – Introduction<br />Project Coin unites all language changes to the Java Lang Specification (JLS) to be added to JDK 7<br />Open call for proposals<br />From February 27, 2009<br />Through March 30, 2009<br />70 proposal forms<br />9 were chosen<br />No Milestone selected yet (so not all features are available)<br />
  48. 48. The Chosen Ones<br />Strings in Switch<br />By Joseph D. Darcy<br />Automatic Resource Management<br />By Joshua Bloch<br />Improved Type Inference for Generic Instance Creation<br />By Jeremy Manson<br />Simplified Varargs Method Invocation<br />By Bob Lee<br />
  49. 49. The Chosen Ones (2)<br />Collection Literals<br />By Joshua Bloch<br />Indexing access syntax for Lists and Maps<br />By Shams Mahmood<br />Language support for JSR 292<br />By John Rose<br />Binary Literals<br />Underscores in numbers<br />By Derek Foster<br />
  50. 50. 1. Strings in Switch<br />
  51. 51. Strings in Switch<br />Syntactic sugar<br />// Finally! - strings in switch<br />String s = "";<br />switch (s) {<br />case"Edno":<br /> out.println("1");<br />break;<br />case"Dve":<br /> out.println("2");<br />break;<br />default:<br /> out.println("Unknown BG number.");<br />break;<br />}<br />
  52. 52. 2. Automatic Resource Management(ARM)<br />
  53. 53. ARM – The Problem<br />A resource is as an object that must be closed manually<br />InputStream, Reader, Writer, Formatter<br />Manual resource termination has proven ugly and error prone<br />Even good programmers get it wrong<br />Resource leaks or even outright failures, which may be silent<br />If an exception is thrown in the try block, and in the finally block, the second supplants the first<br />
  54. 54. ARM – The Problem (2)<br />Where’s the problem with this code?<br />If an exception is thrown in the try block, and in the finally block, the second supplants the first<br />Was "Text" written successfully?<br />BufferedWriter br =<br /> new BufferedWriter(new FileWriter(path));<br />try {<br />br.write("Text");<br />} finally {<br /> br.close();<br />}<br />
  55. 55. How it’s Done (One Resource)<br /><ul><li>Try-finally – with one resource:</li></ul>BufferedWriter br =<br /> new BufferedWriter(new FileWriter(path));<br />try {<br />// This exception is more important<br /> br.write("Text");<br />} finally {<br />try {<br />// ... than this one<br /> br.close();<br /> } catch(IOException ioe) {}<br />}<br />
  56. 56. How it’s Done (Two Resources)<br />staticvoid copy(String src, String dest) throws IOException {<br /> InputStream in = new FileInputStream(src);<br />try {<br /> OutputStream out = new FileOutputStream(dest);<br />try {<br />byte[] buf = newbyte[8 * 1024];<br />int n;<br />while ((n = >= 0)<br /> out.write(buf, 0, n);<br /> } finally {<br />try {<br /> out.close();<br /> } catch(IOException ioe) {}<br /> }<br /> } finally {<br />try {<br /> in.close();<br /> } catch(IOException ioe) {}<br /> }<br />}<br />
  57. 57. Automatic Resource Management<br />ARM statement is a form of the try statement that declares one or more resources<br />The scope of these resource declarations is limited to the statement<br />When the statement completes, whether normally or abruptly, all of its resources are closed automatically<br />As of b89 not yet available, but definitely going to be inside JDK7<br />
  58. 58. <ul><li>Code is still 4 lines
  59. 59. Boilerplate was 11 (try, catch, finally, close() clauses), now it’s 0
  60. 60. The first exception is thrown if a problem occurs, the close() exception is hidden</li></ul>ARM Syntax – Two Resources<br />staticvoid copy(String src, String dest) throws IOException {<br />try (InputStream in = new FileInputStream(src);<br /> OutputStream out = new FileOutputStream(dest)) {<br />byte[] buf = newbyte[8192];<br />int n;<br />while ((n = >= 0)<br /> out.write(buf, 0, n);<br /> }<br />}<br />
  61. 61. An Interface Must be Chosen<br />A class must implement a designated interface to make it eligible for automatic resource management<br />An obvious choice would be Closeable<br />close() method throws IOException<br />Precludes its use in a general purpose resource management facility<br />package;<br />;<br />publicinterface Closeable {<br />publicvoid close() throws IOException;<br />}<br />
  62. 62. An Interface Must be Chosen (2)<br />It is possible to retrofit Closeable with a parameterized superinterface<br />Disposable would become:<br />package java.lang;<br />publicinterface Disposable<X extends Throwable> {<br /> void close() throws X;<br />}<br />package;<br />import;<br />publicinterface Closeable extends Disposable<IOException> {<br /> void close() throws IOException;<br />}<br />
  63. 63. ARM – Notes<br />No interface is chosen, nor implemented yet<br />As of b89<br />Migration<br />Any resource that must be closed manually should be retrofitted to implement the Disposable interface<br />In the JDK, this includes:<br />Closeable (all streams implement it)<br />Connection, Statement, and ResultSet<br />
  64. 64. Proposal Moto<br />New code should use ARM statements for clarity and correctness<br />Existing code can be replaced by ARM for increased clarity and improved behavior<br />Given the number of resource management errors observed in existing code, it may be worth the time to do this systematically<br />Proposal author gives high-profile examples<br />Any modern IDE can search for uses of a method (in this case, Disposable.close())<br />
  65. 65. ARM – Shortcomings<br />"One shortcoming of the construct is that it does not provide a way for the programmer to indicate that exceptions thrown when closing a resource should be ignored"<br />"In the case of the copy method ideally the program would ignore exceptions thrown when closing the InputStream but not the OutputStream"<br />"There are several ways this could be achieved“<br />The proposal does not state what they are<br />
  66. 66. Suppressed Exceptions<br />ARM discards suppressed exceptions<br />Proposal implies they can be saved by adding them in suppressing exception via two new methods to Throwable:<br />void addSuppressedException(Throwable)<br />Throwable[]getSuppressedExceptions()<br />As of b89 not implemented and it’s not clear whether they will be<br />
  67. 67. 3. Improved Type Inference for Generic Instance Creation<br />
  68. 68. The Problem<br />Type inference works on method invocations<br />Type inference does not work on .ctors<br />Google collections solved this by factories<br />package;<br />publicclass Lists {<br /> // ArrayList<br />publicstatic <E> List<E> newArrayList() {returnnew ArrayList<E>();<br /> }<br />publicstatic <E> List<E> newArrayList(int i) {<br />returnnew ArrayList<E>(i);<br /> }<br />}<br />List<String> list = Lists.newArrayList();<br />
  69. 69. What is the Fuss All About?<br />Simply this:<br />… becomes:<br /><> is called the ‘diamond‘<br />Cannot be omitted because no difference can be made between raw HashMap and a parameterized one<br />[Ctrl+Shift+F]failsondiamond in NetBeans 6.9<br />Implemented in b89<br />Map<String, List<String>> anagrams =<br />new HashMap<String, List<String>>();<br />Map<String, List<String>> anagrams = new HashMap<>();<br />
  70. 70. Diamond <>: Quiz<br />Which of these are valid?<br />I think the organizers forgot to give us stuff that we can give away<br />publicstaticvoid main() {<br /> List l = new ArrayList<>();<br />new ArrayList <>().addAll(new ArrayList<>());<br />new ArrayList <>().addAll(new ArrayList<String>());<br />new ArrayList <String>().addAll(new ArrayList<>());<br />}<br />
  71. 71. Diamond <>: Advanced Example<br />This is supposed to work:<br />…but does not yet (as of b89)<br />publicclass AdvancedExample {<br />publicstaticvoid main() {<br /> method("", new ArrayList<>(), new ArrayList<>());<br /> }<br />publicstatic <T> T method(<br /> T a, List<T> b, List<Map<T, T>> c) {<br />return a;<br /> }<br />}<br />
  72. 72. 4. Simplified Varargs Method Invocation <br />
  73. 73. Simplified Varargs Method…<br />The compiler currently generates an "unsafe operation" warning when a programmer tries to invoke a varargs (variable arity) method with a non-reifiablevarargs type<br />This change moves the warning from the call site to the method declaration<br />Major advantages<br />reduces the total number of warnings reported to and suppressed by programmers<br />Enables API designers to use varargs with non-reifiable types<br />
  74. 74. A Picture is Worth a 1000 Words<br />/** NOT WORKING in b89, no change with jdk1.6.0_20 */<br />publicstaticvoid main() {<br /> Callable<String> t = null;<br />//OLD: Warning: "uses unchecked or unsafe operations“<br /> List<Callable<String>> merged = asList(t);<br /> System.out.println(merged);<br />}<br />// NEW: Warning: "unchecked generic array creation"<br />privatestatic <T> List<T> asList(T... elements ) {<br />return Arrays.asList(elements);<br />}<br />
  75. 75. Simplified Varargs – Example<br />interface Sink<T> {<br />void add(T... a);<br />}<br />/** NOT WORKING in b89, no change with jdk1.6.0_20 */<br />interface BrokenSink<T> extends Sink<T> {<br />// OLD: no warning<br />// NEW: Warning: "Overriddes non-reifiable varargs type with array"<br />void add(T[] a);<br />}<br />/** NOT WORKING in b89, no change with jdk1.6.0_20 */<br />class StringSink implements Sink<String> {<br />// OLD: no warning<br />// NEW: Warning: "override generates a more specific varargs type erasure"<br />publicvoid add(String... a) {}<br />}<br />
  76. 76. 5. Collection Literals<br />
  77. 77. Collection Literals<br />Again a syntax sugar<br />Not yet available, so no demo <br />/** NOT WORKING in b89 */<br />publicstaticvoid main(String... args) {<br />List<String> list = ["Edno", "Dve"];<br />Set<String> set = {"Edno", "Dve"};<br />Map<String, Integer> map = {"Edno" : 1, "Dve" : 2};<br />// Note:<br /> Object s = { }; // empty set;<br /> Object m = {:}; // empty map;<br />}<br />
  78. 78. 6. Indexing Access Syntax for Lists and Maps<br />
  79. 79. Collection Literals<br />Syntax sugar<br />/** WORKING in b89 */<br />publicstaticvoid main(String... args) {<br /> List<String> list = <br /> Arrays.asList(new String[]{"a", "b", "c"});<br /> Map<Integer, String> map = <br />new HashMap<Integer, String>(4);<br />// THE OLD WAY<br /> String firstElement = list.get(0);<br /> map.put(1, "Edno");<br />// THE NEW WAY (COMMENTED BECAUSE NOT IMPLEMENTED YET)<br /> String firstElement = list[0];<br /> map[1] = "Edno";<br />}<br />
  80. 80. 7. Language Support for JSR 292<br />
  81. 81. The Da Vinci Machine Project<br />Da Vinci: a multi-language renaissancefor the Java Virtual Machine architecture<br />This project will prototype a number of extensions to the JVM<br />So that it can run non-Java languages efficiently<br />With a performance level comparable to that of Java itself<br />Emphasis is on general purpose extensions<br />Hosted on OpenJDK<br />
  82. 82. The Da Vinci Machine Project (2)<br />Looking to remove “pain points” already observed by implementers of successful or influential languages<br />Sub-projects with major activity include <br />Dynamic invocation<br />Continuations<br />Tail-calls<br />And interface injection<br />Large number of more speculative, lower-priority sub-projects<br />
  83. 83. JSR 292 Support in javac<br />java.dyn.InvokeDynamic will accept any method call and turn it into an invokedynamic instruction<br />The type java.dyn.MethodHandle will accept any argument and return types<br />Bytecode names acceptable to the JVM can be spelled from Java code, using #" "<br />java.dyn.InvokeDynamic serves as a bare reference type: anything implicitly converts to it<br />it can be cast to anything, but it is not a subtype of java.lang.Object<br />
  84. 84. JSR 292 – Example<br />// Works in b89<br />// type (Object, int) -> boolean<br />boolean z = <br /> java.dyn.InvokeDynamic.<boolean>myEquals(x, y);<br />// Works!!! in b89<br />MethodHandle hndl = MethodHandles.lookup().findVirtual(<br /> PrintStream.class, "println", MethodType.methodType(<br />void.class, String.class));<br />hndl.invokeGeneric(System.out, "holy cow?!");<br />// Works in b89<br />String #"g 1 $!$#%" = "Text";<br />System.out.println(#"g 1 $!$#%");<br />
  85. 85. 9. Underscores in Numbers<br />
  86. 86. Underscores in Numbers<br /><ul><li>Too much sugar can cause diabetes
  87. 87. May seem useless,butdon’tjudgetooquickly</li></ul>/** WORKING in b89 */<br />publicstaticvoid main(String... args) {<br />// THE OLD WAY<br />int oldBillion = 1000000000;<br />// THE NEW WAY<br />int newBillion = 1_000_000_000;<br /> out.println(oldBillion);<br /> out.println(newBillion);<br />}<br />
  88. 88. 10. Binary Literals<br />
  89. 89. Binary Literals<br /><ul><li>The syntax is 0b11110000;
  90. 90. See where underscores come in handy?</li></ul>/** WORKING in b89 */<br />publicstaticvoid main(String... args) {<br />// THE OLD WAY<br />int oldBinary1 = 153;<br />int oldBinary2 = 128 ^ 0 ^ 0 ^ 16 ^ 8 ^ 0 ^ 0 ^ 1;<br />// THE NEW WAY<br />int newBinary = 0b1001_1001;<br /> out.println(oldBinary1);<br /> out.println(oldBinary2);<br /> out.println(format("[0b1001_1001] is {0}", newBinary));<br />}<br />
  91. 91. Closures in Java<br />First-class Functions, Function Types and Lambda Expressions<br />
  92. 92. What are Closures?<br />Closures – definition<br />Closures are functions that are evaluated in an environment containing one or more bound variables [Wikipedia]<br />In English: a little snippet of code (function) that can be passed as argument of some method for subsequent execution<br />Closures come from functional programming languages like Lisp<br />Limited support for closures since JDK 1.1, in the form of anonymous classes<br />
  93. 93. First-class and Anonymous Functions<br />First-class functionsare programming paradigm that supports<br />Data structure holding a function with its parameters and return type<br />Passing functions as arguments to other functions and invoking them<br />Returning functions as result<br />Anonymous functions<br />Functions without name (lambda functions)<br />Take some parameters and return a value<br />
  94. 94. Lambda Expressions<br />Lambda calculus<br />A formal mathematical system for function definition, function application and recursion<br />Typed and untyped lambda calculus<br />Lambda expressions<br />Anonymous functions that take parameters and return values, e.g.<br />x -> x*x<br />(x, y) -> x*x + y*y<br />A.k.a. lambda functions<br />
  95. 95. Project Lambda<br />Project Lambda<br />Goals<br />To formulate a proposal to add first-class functions, function types, and lambda expressions (informally, "closures") to Java<br />To implement a prototype suitable for inclusion in JDK 7<br />Official Web Site<br /><br />Status<br />Straw-man proposal, still no JSR<br />
  96. 96. Lambda Expressions in Java<br />Lambda expressions in Java use the # syntax<br />Function with no arguments, returns 42:<br />Function with int argument:<br />Function with two int arguments:<br />#()(42)<br />#(int x)(x + x)<br />#(int x, int y)(x * y)<br />
  97. 97. Lambda Expressions with Code Block<br />Lambda expressions can have body<br />A Java code block:<br />#(int x, int y) { <br /> int z = (int)Math.sqrt(x*x + y*y);<br /> if (z < 10) <br /> return x;<br /> else if (z > 10) <br /> return y; <br /> else<br /> return 0;<br />}<br />
  98. 98. Function Types<br />Function types are data types that hold a reference to lambda function or method:<br />Functions stored in variable of function type can be invoked like any other function:<br />#int() fortyTwo = #()(42);<br />#int(int) triple = #(int x)(3*x); #int(int,int) mult = #(int x, int y)(x * y); <br />System.out.println(fortyTwo());<br />int result = triple(5);<br />int multResult = mult(3, 5);<br />
  99. 99. Functions as Arguments<br />Lambda functions can be passed as arguments to a method<br />public long sum(int[] arr, #int(int) fn) {<br /> long sum = 0;<br /> for (int element : arr)<br /> sum += fn(element);<br /> return sum;<br />}<br />int[] arr = new int[] {1, 2, 3, 4};<br />long squaresSum = sum(arr, #(int x)(x*x));<br />System.out.println(squaresSum); // 30<br />
  100. 100. Functions as Return Value<br />Lambda functions can be returned as result of method execution:<br />public #int(int) adder(int c) { <br /> return #(int x)(x + c);<br />}<br />#int(int) a42 = adder(42);<br />System.out.println(a42(2)); // 44<br />
  101. 101. Function Conversions<br />Lambda functions can be converted to abstract class / interface defining a single method:<br />Thread th = new Thread(new Runnable() {<br /> public void run() { <br /> doSomeStuff();<br /> doMoreStuff(); <br /> } <br />});<br />Thread th = new Thread(#(){ <br /> doSomeStuff(); doMoreStuff(); } )<br />
  102. 102. Variable Capture<br />We can share local state between the body of a lambda expression and its enclosing scope<br />A new keyword shared is introduced<br />shared int comparisonsCount = 0;<br />Collections.sort(data, #(String a, String b) { <br /> comparisonsCount++;<br /> return a.compareTo(b);<br />});<br />System.out.println(comparisonsCount); <br />
  103. 103. Instance Capture<br />The this reference of the enclosing class could be accessed in a lambda expression:<br />class CountingSorter { <br /> private int comparisonsCount = 0;<br /> Collections.sort(data, <br /> #(String a, String b) { <br /> comparisonsCount++;<br /> return a.compareTo(b);<br /> }<br />);<br />
  104. 104. Extension Methods<br />Extension methods allow the author of an existing interface to add methods to that interface while preserving compatibility<br />For example, we need to add a method for filtering members from any collection by given Boolean condition:<br />Set<Integer> set = <br /> new Set<Integer>(new int[] {1,2,3,4,5});<br />Set<Integer> filteredSet =<br /> set.filter(#boolean(int x)(x < 3));<br />
  105. 105. Extension Methods (2)<br />Defining extension methods:<br />class Collections {<br /> …<br /> static <T> Set<T> filter(<br /> Set<T> s, #boolean(T) pred) { … } <br /> static <S,T> Set<S> map(<br /> Set<T> s, #S(T) func) { … }<br />}<br />interface Set<T> extends Collection<T> {<br /> …<br /> Set<T> filter(#boolean(T)) import static<br /> Collections.filter;<br /> <S> map(#S(T)) import static;<br />}<br />
  106. 106. Extension Methods (3)<br />Using extension methods:<br />int ints = new int[] { 1, 2, 3, 4, 5 };<br />int[] transformedInts = <br /> s.filter(#(int x)(x % 2 == 0))<br /> .map(#(int x)(x + 3));<br />// transformedInts = { 5, 7 }<br />int[] transformedInts =<br /><br /> Collections.filter(s, #(int x)(x % 2 == 0)),<br /> #(int x)(x + 3)<br />); <br />
  107. 107. Parallel Arrays API<br />The class ParallelArray<T> allows parallel aggregate operations over a collection<br />Apply transformation to each element<br />Map each element to a new element<br />Select subset of the elements by predicate<br />Reduce elements to a single value (e.g. sum)<br />ParallelArray<T> can utilize efficiently multi-core / multiprocessor systems<br />Ideal candidate for extension methods<br />
  108. 108. Upgrade Class-Loader Architecture<br />
  109. 109. The Problem<br />Bug ID: 4670071<br />Submit Date: 17-APR-2002<br />Release Fixed: 7(b47)<br />Means: Fixed in JDK7 (build 47)<br />b47 got released Q1 2009<br />The bug is about a classloader deadlock<br />deadlocks as caused by non-interceptibleloadClassInternal() calls<br />How many of you know about the existence of bug 4670071?<br />
  110. 110. Method to close a URLClassLoader<br />
  111. 111. Introduction<br />Complex Java programs sometimes create their own class loaders using the URLClassLoader type<br />With it applications can load classes and resources from a search path of URLs:<br />file:<br />jar:<br />http:<br />which load from directories, jar files, and http servers respectively<br />
  112. 112. The Problem<br />A frequent problem has been how to support updated implementations of loaded classes<br />In principle, once the application clears all references to a loader object, the garbage collector will eventually ensure that all resources are released and closed<br />Applications need to be able to do this in a predictable and timely fashion<br />It is a particular problem on Windows, because open files cannot be deleted or replaced<br />
  113. 113. A Simple Solution<br />To alleviate this problem, URLClassLoader has acquired a new method called close()<br />since b48 of JDK 7<br />Invalidates the loader, so that no new classes can be loaded from it<br />It also closes any jar files that were opened by the loader<br />This allows the application to delete/replace these files and if necessary create new loaders using new implementations<br />/** @since 1.7 */ urlClassLoader.close();<br />
  114. 114. Unicode 5.1<br />
  115. 115. Introduction<br />Java 6 is Unicode 4.0 compliant<br />Java 7 will be Unicode 5.1 compliant<br />Most up-to-date version of Unicode is 5.2 (October 2009)<br />What's new in Unicode 5 ?<br />Unicode 5.0 will include 1,369 new characters and 9 new blocks (~alphabets)<br />Unicode 5.1 will have 1,624 additional char’s making a grand total of 100,713 breaking the 100K mark for the first time<br />
  116. 116. 5.0 Phoenician Controversy<br />The Phoenician (Финикийски език) "debate“ will be remembered with disgust for many years to come<br />Thousands of postings on the Unicode public mailing list <br />Diametrically opposed  (and immovable) positions<br />Finally in 5.1: the enigmatic Phaistos Disc<br />First proposed for encoding ten years ago<br />Delayed because there were undeciphered symbols found on a unique artifact<br />
  117. 117. JSR 203:More New I/O APIs for the Java Platform(NIO.2)<br />
  118. 118. NIO2 – Introduction<br />New I/O or non-blocking I/O, usually called NIO, is a collection of Java programming language APIs that offer features for intensive I/O operations<br />It was introduced with the J2SE 1.4 <br />NIO was developed under the Java Community Process as JSR 51<br />As of 2006, an extension to NIO, called NIO2, is being developed under JSR 203<br />JSR 203 is scheduled to be included in JDK 7<br />
  119. 119. How to Copy a File<br />Up to Java 6 (w/o channels) it looks like this:<br />Familiar?<br />The presenter learned this pattern 8 years ago(Ironically taught by the other presenter)<br />try {<br /> from = new FileInputStream(fromFile);<br /> to = new FileOutputStream(toFile);<br />byte[] buffer = newbyte[4096];<br />int bytesRead;<br />while ((bytesRead = != -1)<br /> to.write(buffer, 0, bytesRead); // write<br />} finally {<br /> // Close to and from<br />}<br />
  120. 120. How to Copy a File (2)<br /> is used to represent a file<br />@since 1.0<br />Is there a way to copy metadata?<br />JDK7: -> java.nio.file.Path<br /> won’t be deprecated, but should<br />Path is a better name (might be a dir, right?)<br />FileSystem local = FileSystems.getDefault();<br />Path from = local.getPath(FileName);<br />Path to = local.getPath(toFileName);<br />from.copyTo(to);<br />// -> java.nio.filePath<br />Path p = new File("/foo/bar.txt").toPath();<br />
  121. 121. Cool New Things: resolve()<br />resolve()<br />publicstaticvoid resolve() {<br /> FileSystem fileSystem = FileSystems.getDefault();<br /> Path currentDir = fileSystem.getPath(".");<br /> Path srcDir = fileSystem.getPath("src");<br /> Path file1 = fileSystem.getPath("./");<br /> Path file2 = fileSystem.getPath(“../");<br /> System.out.println("file2: " + currentDir.resolve(srcDir).resolve(file2));<br />}<br />
  122. 122. Cool New Things: relativize()<br />relativize()<br />publicstaticvoid relativize() {<br /> FileSystem fileSystem = FileSystems.getDefault();<br /> Path source = fileSystem.getPath(".");<br /> Path temp = fileSystem.getPath("/temp");<br /> Path relativeSource =<br /> source.toAbsolutePath(). relativize(temp.toAbsolutePath());<br /> System.out.println(relativeSource);<br />}<br />
  123. 123. SCTP (Stream Control Transmission Protocol)<br />
  124. 124. SCTP<br />Stream Control Transmission Protocol (SCTP) is a Transport Layer protocol<br />serving in a similar role as TCP and UDP<br />Features of SCTP include:<br />Multihoming support: both endpoints of a connection can consist of more than one IP<br />Chunks delivered within independent streams<br />Protect against flooding attacks<br />No Windows supports SCTP<br />
  125. 125. JDK7: The SCTP Project<br />The goal of this Project is:<br />To develop an API for the Stream Control Transport Protocol (SCTP)<br />And a corresponding OpenJDK prototype<br />The API is implementation agnostic<br />Included in build 56<br />Could be hacked to work with JDK6<br />Currently only Solaris is supported<br />
  126. 126. SDP (Sockets Direct Protocol)<br />
  127. 127. SDP<br />The Sockets Direct Protocol (SDP) is a networking protocol originally defined by the InfiniBand Trade Association<br />Transport agnostic protocol for Remote Direct Memory Access (RDMA)<br />RDMA is a direct memory access from one computer’s memory into another’s without involving either one's operating system<br />JDK7’s SDP implementation works, unfortunately, only on Solaris<br />
  128. 128. Java 7 New Features<br />Questions?<br />
  129. 129. Resources – Java Chronology<br />JDK 7 – Features<br /><br />JDK 7 – Milestones<br /><br />
  130. 130. Resources – Compressed oops<br />Compressed oops in the Hotspot JVM<br /><br />Wikipedia – 64-bit<br /><br />ILP32, LP64, and LLP64<br /><br />C Programming Language<br /><br />
  131. 131. Resources – Garbage Collection<br />Garbage-First Garbage Collection<br /><br />JavaOne: G1 Garbage Collector<br /><br />Garbage Collection – Wikipedia<br /><br />Wikipedia – Hard and Soft Real-time Systems<br /><br />
  132. 132. Resources – Dynamic Langs<br />New JDK 7 Feature: Support for Dynamically Typed Languages in the Java Virtual Machine<br /><br />John Rose's weblog at Sun Microsystems<br /><br />JSR 292: Supporting Dynamically Typed Languages on the Java Platform<br /><br />
  133. 133. Resources – Project Jigsaw<br />Project Jigsaw: Language changes for Modules<br /><br />Project Jigsaw – Mark Reinhold’s Blog<br /><br />Is the JDK Losing its Edge(s)?<br /><br />
  134. 134. Resources – JSR 308<br />Type Annotations Specification (JSR 308)<br /><br />Type Annotations FAQ (JSR 308)<br /><br />The Checker Framework: Custom Pluggable Types for Java<br /><br />
  135. 135. Resources – Project Coin<br />Project Coin<br /><br /><br />Strings in switch<br /><br />Automatic Resource Management<br /><br />
  136. 136. Resources – Project Coin (2)<br />Improved Type Inference for Generic Instance Creation<br /><br />Simplified Varargs Method Invocation<br /><br />Collection Literals<br /><br />
  137. 137. Resources – Project Coin (3)<br />Indexing access syntax for Lists and Maps<br /><br />Language support for JSR 292<br /><br />Binary Literals<br /><br />Underscores in numbers<br /><br />
  138. 138. Resources – Closures<br />Project Lambda<br /><br />Project Lambda: Straw-Man Proposal<br /><br />Closures for Java – Mark Reinhold’s Blog<br /><br />
  139. 139. Resources – Upgrade ClassLoader Architecture<br />Draft Proposal for ClassLoader Deadlock Fix<br /><br />java.lang.ClassLoader.loadClassInternal(String)is Too Restrictive<br /><br />
  140. 140. Resources – URL ClassLoader<br />Closing a URLClassLoader<br /><br />Class URLClassLoader – close()<br /><br />
  141. 141. Resources – Unicode 5.1<br />JDK 7 – Features – Unicode 5.1<br /><br />What's new in Unicode 5.0?<br /><br />What's new in Unicode 5.1? <br /><br />
  142. 142. Resources – NIO2<br />Java New I/O<br /><br />JSR 203: The Open Road – java.nio.file<br /><br />
  143. 143. Resources – SCTP<br />SCTP Project<br /><br />
  144. 144. Resources – SDP<br />Understanding the Sockets Direct Protocol<br /><br />Sockets Direct Protocol – Wikipedia<br /><br />Remote Direct Memory Access<br /><br />Zero-copy<br /><br />
  145. 145. Resources – Authors<br />Mihail Stoynov<br /><br />Svetlin Nakov<br /><br />