1 / 121

Java 7 – New Features

Java 7 – New Features. Svetlin Nakov, Mihail Stoynov. Bulgarian Association of Software Developers. BGJUG, TU-Sofia, hall 2140 20.05.2010. www.devbg.org. About the Speakers. Svetlin Nakov 15+ years software engineering experience PhD in computer science from Sofia University

pia
Download Presentation

Java 7 – New Features

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java 7 – New Features Svetlin Nakov, Mihail Stoynov Bulgarian Association of Software Developers BGJUG, TU-Sofia, hall 2140 20.05.2010 www.devbg.org

  2. About the Speakers • Svetlin Nakov • 15+ years software engineering experience • PhD in computer science from Sofia University • Chairman of the Bulgarian Association of Software Developers (BASD) – www.devbg.org • Author of 6 books about Java, .NET and software engineering • Blog: www.nakov.com/blog/

  3. About the Speakers (2) • Mihail Stoynov • Dev Lead, Materna Bulgaria • Many years software engineering experience with Java, .NET and others • Blog: http://mihail.stoynov.com/blog/

  4. Table of Contents • Java 7 – Introduction and Chronology • Dynamic Languages in JVM • Java Modularity – Project Jigsaw • Language Enhancements (Project Coin) • Closures for Java • JSR 203: NIO 2 • Other new features: • Compressed 64-bit oops, Garbage-First GC, Upgraded Class-Loaders, URLClassLoader. close(), Unicode 5.1, SCTP and SDP

  5. Introduction and Chronology

  6. OpenJDK JDK7 is the second JDK done via the OpenJDK effort OpenJDK is free, open-source and GPL licensed A lot of the improvements of JDK7 are separate projects on OpenJDK Some say that projects go under the cap of OpenJDK to avoid the cumbersome and slow JCP process

  7. Java 7 – Milestones Began in August 2006 First supposed to be 7 milestones Mark Reinhold extended them to 10 Current status: M7 finished, presentation made with build89 M10 expected to finish 09.09.2010 “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”

  8. There’s No JSR Yet A Java 7 JSR is supposed to be formed Java SE 6 was under the 'Umbrella' JSR 270 JDK7 is in Eclipse’s low priority list because a lack of container JSR JDK7 cannot be finalized without a JSR There are some functionalities that also lack a JSR While doing this presentation we used the term JSR TBD in lieu of the missing JSR

  9. Source Control System Official SCM is SVN, still Note: it takes a 'while' (e.g. one night) Unofficial Mercurial forest repositories available since November 2007 Note: this also takes a 'while' >svn co https://jdk7.dev.java.net/svn/jdk7/trunk >hg fclone http://hg.openjdk.java.net/

  10. Currently Supported IDEs Eclipse Both Eclipse 3.6M6 and E4 do not support JDK7’s syntax … or I couldn’t figure it out  Strangely enough the option is there: Source compatibility: 1.7 NetBeans 6.9 Beta supports JDK7 Compiles successfully the M7 syntax

  11. Dynamic Languages in JVM

  12. The Da Vinci Machine Project Prototype a number of extensions to the JVM A.k.a. Multi Language Virtual Machine –http://openjdk.java.net/projects/mlvm/ Allows non-Java dynamic languages to run efficiently in the JVM Emphasis is on general purpose extensions Hosted on OpenJDK • Da Vinci: a multi-language renaissancefor the Java Virtual Machine architecture

  13. Dynamic Languages in JVM • Da Vinci Machine sub-projects include: • Dynamic invocation • Continuations • Tail-calls • And interface injection • JSR 292: Supporting Dynamically Typed Languages on the Java Platform • The standard behind Da Vinci Machine • Natural continuation of JSR 223: Scripting for the Java Platform implemented in JDK 6

  14. Dynamic Languages in JVM (2) • New JVM instruction invokedynamic • Allows extremely fast dynamic method invocation through method handles • Will enable JRuby, Jython, Groovy and other dynamic and scripting languages to call dynamic methods natively at bytecode level • Method handles • Lightweight references to a method – java.dyn.MethodHandle • Anonymous classes in the JVM

  15. Dynamic Languages in JVM (3) • Autonomous methods • Methods that can be dynamically attached to an existing class at runtime • Interface injection • Acquiring base interfaces and method implementations at runtime • Continuations and stack introspection • Suspend / resume thread's execution stack • Tail calls and tail recursion

  16. Dynamic Languages in JVM (4) • Runtime support for closures • Closure is a lambda-expression bound (closed) to its environment • Multimethods • Dispatch a method overload depending on the actual arguments at runtime • Faster reflection and faster interface invocation based on dynamic invocation • Symbolic freedom for identifier names

  17. Dynamic Invoke – Example staticvoid greeter(String x) { System.out.println("Hello, " + x); } static MethodHandle greeterMethodHandle = MethodHandles.lookup().findStatic( DynamicInvocation.class, "greeter", MethodType. methodType(void.class, String.class)); static { Linkage.registerBootstrapMethod( "bootstrapDynamic"); }

  18. Dynamic Invoke – Example (2) privatestatic CallSite bootstrapDynamic( Class caller, String name, MethodType type) { if (type.parameterCount() == 1 && name == "hail") { MethodHandle target = MethodHandles. convertArguments(greeterMethodHandle, type); CallSite site = new CallSite(caller, name, type); site.setTarget(target); System.out.println("Set the CallSite target to " + greeterMethodHandle); return site; } } publicstaticvoid main(String... args) { InvokeDynamic.hail("dynamic invocation"); }

  19. Java Modularity Project Jigsaw

  20. Modularization – Introduction The JDK and the JRE, have always been delivered as massive, indivisible artifacts The growth of the platform has thus inevitably led to the growth of the basic JRE download which now stands at well over 14MB despite heroic engineering efforts such as the Pack200 class file compression format Java Kernel and Quickstarter features do improve download time and startup time, at least for Windows users

  21. The Real Solution The most promising way to improve the key metrics of Download time Startup time And memory footprint Is to attack the root problem head-on: Divide the JDK into a set of well specified and separate, yet interdependent, modules A side effect is that JAR format has to reworked

  22. Alan Bateman: It’s Difficult Suppose you are using the Logging API Logging requires NIO (for file locking) And JMX (as loggers are managed) JMX requires JavaBeans, JNDI, RMI and CORBA (JMX remote API mandates that the RMI connector support both JRMP and IIOP) JNDI requires java.applet.Applet (huh?) and JavaBeans has dependencies on AWT, Swing Not satisfied with this, JavaBeans has persistent delegates that create dependencies on JDBC and more

  23. How to Do It? Modularizing the JDK requires a module system capable of supporting such an effort It requires, in particular, a module system whose core can be implemented directly within the Java virtual machine Modularizing is best done with a module system that’s tightly integrated with the Java language Otherwise the compile-time module environment can differ dramatically from the run-time module environment

  24. Which Module System? JSR 277 proposes the JAM module system Some of its rich, non-declarative features would be impossible to implement its core functionality directly within the JVM Therefore Sun halted the development JSR 294 is chartered to extend the language and JVM to support modular programming Well received for its simplicity and its utility to existing module systems such as OSGi

  25. Which Module System? (2) OSGi May 2007: OSGi 4.1 standardized as JSR-291 Reasonably mature, stable, and robust Implemented within Apache Harmony JVM Not at all integrated with the Java language Jigsaw created to modularize JDK7 Will not be an official part of the Java SE 7 Platform Specification and might not be supported by other SE 7 implementations

  26. Status and Examples Probably JSR 294 will be chosen There are issues, JSR 294 is inactive (paused) Not implemented yet (b89), java.lang.module Example (may, and probably will, change) module M1@1.0 provides M2@2.0, M3@3.0 { requires M4@4.0, M5@5.0; permits M6; // only M6 can depend on M1 } module M; package P; publicclassFoo {...}

  27. JSR 308:(Extended) Annotations on Java Types

  28. JSR 308 – Introduction Java SE 6 permits annotations only on declarations JSR 308 extends Java’s annotation system so that annotations may appear on nearly any use of a type JSR 308 is backward-compatible and continues to permit those annotations Two new types of annotations (target wise): ElementType.TYPE_USE ElementType.TYPE_PARAMETER

  29. JSR 308: Examples publicstaticvoid main() { //for generic type arguments in a generic method JSR308Example2.<@NonNull String>method("..."); //for type parameters and type parameter bounds: Collection<@Long ? super@Existing File> c = null; //for class inheritance: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { } } //for throws clauses: void monitorTemperature() throws@Critical Exception {} //for method receivers: public String toString() @Readonly { returnnull; } // helper only publicstatic <T> T method(String s) {returnnull;}

  30. Small Language Enhancements (Project Coin)

  31. Project Coin – Introduction Project Coin unites all language changes to the Java Lang Specification (JLS) to be added to JDK 7 Open call for proposals From February 27, 2009 Through March 30, 2009 70 proposal forms 9 were chosen No Milestone selected yet (so not all features are available)

  32. The Chosen Ones Strings in Switch By Joseph D. Darcy Automatic Resource Management By Joshua Bloch Improved Type Inference for Generic Instance Creation By Jeremy Manson Simplified Varargs Method Invocation By Bob Lee

  33. The Chosen Ones (2) Collection Literals By Joshua Bloch Indexing access syntax for Lists and Maps By Shams Mahmood Language support for JSR 292 By John Rose Binary Literals Underscores in numbers By Derek Foster

  34. 1. Strings in Switch

  35. Strings in Switch Syntactic sugar // Finally! - strings in switch String s = ""; switch (s) { case"Edno": out.println("1"); break; case"Dve": out.println("2"); break; default: out.println("Unknown BG number."); break; }

  36. 2. Automatic Resource Management (ARM)

  37. ARM – The Problem A resource is as an object that must be closed manually InputStream, Reader, Writer, DB connection Manual resource termination has proven ugly and error prone Even good programmers get it wrong Resource leaks or even outright failures, which may be silent If an exception is thrown in the try block, and in the finally block, the second supplants the first

  38. ARM – The Problem (2) Where’s the problem with this code? If an exception is thrown in the try block, and in the finally block, the second supplants the first Was "Text" written successfully? BufferedWriter br = new BufferedWriter(new FileWriter(path)); try{ br.write("Text"); } finally { br.close(); }

  39. How It’s Done (One Resource) • Try-finally – with one resource: BufferedWriter br = new BufferedWriter(new FileWriter(path)); try{ // This exception is more important br.write("Text"); } finally { try { // ... than this one br.close(); } catch(IOException ioe) {} }

  40. How It’s Done (Two Resources) staticvoid copy(String src, String dest) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = newbyte[8 * 1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { try { out.close(); } catch(IOException ioe) {} } } finally { try { in.close(); } catch(IOException ioe) {} } }

  41. ARM Syntax – Two Resources • Code is now 4 lines • Removed the boring nested try, catch, finally, close()clauses • The first exception is thrown if a problem occurs, the close() exception is hidden staticvoid copy(String src, String dest) throws IOException { try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest)) { byte[] buf = newbyte[8192]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } }

  42. Automatic Resource Management ARM statement is a form of the try statement that declares one or more resources The scope of these resource declarations is limited to the statement When the statement completes, whether normally or abruptly, all of its resources are closed automatically As of b89 ARM is not yet available, but definitely going to be inside JDK7

  43. An Interface Must be Chosen A class must implement a designated interface to make it eligible for automatic resource management An obvious choice would be Closeable close() method throws IOException What about general purpose resources? package java.io; importjava.io.IOException; publicinterface Closeable { publicvoid close() throws IOException; }

  44. An Interface Must be Chosen (2) It is possible to retrofit Closeable with a parameterized superinterface Disposable would become: package java.lang; publicinterface Disposable<X extends Throwable> { void close() throws X; } package java.io; import java.io.IOException; publicinterface Closeable extends Disposable<IOException> { void close() throws IOException; }

  45. ARM – Notes No interface is chosen, nor implemented yet As of b89 Migration Any resource that must be closed manually should be retrofitted to implement the Disposable interface In the JDK, this includes: Closeable (all streams implement it) Connection, Statement, and ResultSet

  46. Suppressed Exceptions ARM discards suppressed exceptions Proposal implies they can be saved by adding them in suppressing exception via two new methods to Throwable: void addSuppressedException(Throwable) Throwable[]getSuppressedExceptions() As of b89 not implemented and it’s not clear whether they will be

  47. 3. Improved Type Inference for Generic Instance Creation

  48. What is the Fuss All About? Simply this: … becomes: <> is called the ‘diamond‘ Cannot be omitted because no difference can be made between raw HashMap and a parameterized one [Ctrl+Shift+F]failsondiamond in NetBeans 6.9 Implemented in b89 Map<String, List<String>> anagrams = new HashMap<String, List<String>>(); Map<String, List<String>> anagrams = new HashMap<>();

  49. Diamond <>: Advanced Example This is supposed to work: …but does not yet (as of b89) publicclass AdvancedExample { publicstaticvoid main() { method("", new ArrayList<>(), new ArrayList<>()); } publicstatic <T> T method( T a, List<T> b, List<Map<T, T>> c) { return a; } }

  50. 4. Simplified Varargs Method Invocation

More Related