Wednesday, November 16, 11

Top 10 things to know about Java SE 7 Danny Coward Principal Engineer

Wednesday, November 16, 11 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

3 Wednesday, November 16, 11 Java SE 7 Top 10

1. Project Coin

4 Wednesday, November 16, 11 coin, n. A piece of small change coin, v. To create new language

5 Wednesday, November 16, 11 Evolving the Language From “Evolving the Java Language” - JavaOne 2005 • Java language principles – Reading is more important than writing – Code should be a joy to read – The language should not hide what is happening – Code should do what it seems to do – Simplicity matters – Every “good” feature adds more “bad” weight – Sometimes it is best to leave things out • One language: with the same meaning everywhere • No dialects • We will evolve the Java language • But cautiously, with a long term view • “first do no harm”

6 Wednesday, November 16, 11 Better Integer Literals

• Integer literals int mask = 0b101010101010; aShort = (short)0b1010000101000101; long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

• With underscores for clarity

int mask = 0b1010_1010_1010; long big = 9_223_783_036_967_937L;

7 Wednesday, November 16, 11 :) Literals

HAPPY_FACE = { (short)0b0000011111100000; (short)0b0000100000010000; (short)0b0001000000001000; (short)0b0010000000000100; (short)0b0100000000000010; (short)0b1000011001100001; (short)0b1000011001100001; (short)0b1000000000000001; (short)0b1000000000000001; (short)0b1001000000001001; (short)0b1000100000010001; (short)0b0100011111100010; (short)0b0010000000000100; (short)0b0001000000001000; (short)0b0000100000010000; (short)0b0000011111100000; }

8 Wednesday, November 16, 11 Recognize any of these numbers ?

314159265 311385876 3315643000000 299792458 53500000000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 311_385_876 3_315_643_000_000 299_792_458 53_500_000_000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 π 311_385_876 3_315_643_000_000 299_792_458 53_500_000_000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 π 311_385_876 est. US population 3_315_643_000_000 299_792_458 53_500_000_000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 π 311_385_876 est. US population 3_315_643_000_000 German GDP 2010 299_792_458 53_500_000_000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 π 311_385_876 est. US population 3_315_643_000_000 German GDP 2010 299_792_458 m/s 53_500_000_000

9 Wednesday, November 16, 11 Recognize any of these numbers ?

3_14159265 π 311_385_876 est. US population 3_315_643_000_000 German GDP 2010 299_792_458 c m/s 53_500_000_000 Carlos Slim net worth

9 Wednesday, November 16, 11 Strings in Switch statements

• Today case label includes integer constants and enum constants • Strings are constants too (immutable)

10 Wednesday, November 16, 11 int monthNameToDays(String s, int year) { if (s.equals(“April”) || s.equals(“June”) || s.equals(“September”) || s.equals(“November”)) return 30; if (s.equals(“January”) || s.equals(“March”) || s.equals(“May”) || s.equals(“July”) || s.equals(“August”) || s.equals(“December”)) return 31; if (s.equals()) ... else ... } 11 Wednesday, November 16, 11 int monthNameToDays(String s, int year) { switch(s) { case “April”: case “June”: case “September”: case “November”: return 30; case “January”: case “March”: case “May”: case “July”: case “August”: case “December”: return 31; case “February”: ... default ... }

11 Wednesday, November 16, 11 Diamond Operator

Map map1 = new HashMap(); Map> map2 = new HashMap>(); Map>> map3 = new HashMap>>();

Wednesday, November 16, 11 Diamond Operator

Map map1 = new HashMap<>(); Map> map2 = new HashMap<>(); Map>> map3 = new HashMap<>();

Wednesday, November 16, 11 Copying a File

InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest);

byte[] buf = new byte[8192]; int n;

while (n = in.read(buf)) >= 0) out.write(buf, 0, n);

in.close(); out.close();

13 Wednesday, November 16, 11 Copying a File

InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest);

try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { in.close(); out.close(); }

14 Wednesday, November 16, 11 Copying a File

InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); } } finally { in.close(); }

15 Wednesday, November 16, 11 Copying a File

InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); } } finally { Exception thrown from in.close(); potentially three places. } Details of first two could be lost

16 Wednesday, November 16, 11 try-with-resources syntax

try (InputStream in = new FileInputStream(src), OutputStream out = new FileOutputStream(dest)) { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); }

17 Wednesday, November 16, 11 try-with-resources syntax

try ResourceSpecification Block Catchesopt Finallyopt

18 Wednesday, November 16, 11 try-with-resources syntax

• Compiler desugars try-with-resources into nested try- finally blocks with variables to track exception state • ‘Lost’ exceptions are recorded for posterity using a new facility of Throwable - addSuppressedException • API support in JDK 7 • anything with a void close() method is a candidate for use with this syntax • i.e. anything implementing java.io.Closeable or its new superinterface java.lang.AutoCloseable • JDBC 4.1 retrofitted as AutoCloseable too

19 Wednesday, November 16, 11 More Informative Backtraces

java.io.IOException at Suppress.write(Suppress.java:19) at Suppress.main(Suppress.java:8) Suppressed: java.io.IOException 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)

20 Wednesday, November 16, 11 Multi-catch with More Precise Rethrow

try { // Reflective operations calling Class.formName, // Class.newOnstance, Class.getMethod, Method.invoke, etc. } catch (ClassNotFoundException cnfe) { log(cnfe) throw cnfe; } catch (InstantiationException ie) { log(ie); throw ie; } catch (NoSuchMethodException nsme) { log(nsme); throw nsme; } catch (InvocationTargetException ite) { log(ite); throw ite; }

21 Wednesday, November 16, 11 Tempting...

try { // Reflective operations calling Class.formName, // Class.newInstance, Class.getMethod, Method.invoke, etc. } catch (Exception e) { log(e) throw e; }

22 Wednesday, November 16, 11 Exception by-catch

try { // Reflective operations calling Class.formName, // Class.newOnstance, Class.getMethod, Method.invoke, etc. } catch (Exception e) { log(e) throw e; } Catches both checked and unchecked exceptions

23 Wednesday, November 16, 11 Exception by-catch

try { // Reflective operations calling Class.formName, // Class.newOnstance, Class.getMethod, Method.invoke, etc. } catch (RuntimeException re) { ... } catch (Exception e) { log(e) throw e; } Better

24 Wednesday, November 16, 11 Multi-catch - best

try { // Reflective operations calling Class.formName, // Class.newOnstance, Class.getMethod, Method.invoke, etc. } catch (ClassNotFoundException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { log(e) throw e; }

25 Wednesday, November 16, 11 Java SE 7 Top 10

2. NIO2

26 Wednesday, November 16, 11 New I/O 2 (NIO2) Libraries JSR 203

• Original Java I/O APIs presented challenges for developers • Not designed to be extensible • Many methods do not throw exceptions as expected • rename() method works inconsistently • Developers want greater access to file metadata • Java NIO2 solves these problems

27 Wednesday, November 16, 11 Java NIO2 API Features

• Path is a replacement for File • Biggest impact on developers • Better directory support • list() method can stream via iterator • Entries can be filtered using regular expressions in API • Symbolic link support • java.nio.file.Filesystem • interface to a filesystem (FAT, ZFS, Zip archive, network, etc) • java.nio.file.attribute package • Access to file metadata

28 Wednesday, November 16, 11 The Path Class

• Equivalent of java.io.File in the new API – Immutable • Have methods to access and manipulate Path • Few ways to create a Path – From Paths and FileSystem

//Make a reference to the path Path home = Paths.get(“/home/fred”); //Resolve tmp from /home/fred -> /home/fred/tmp Path tmpPath = home.resolve(“tmp”); //Create a relative path from tmp -> .. Path relativePath = tmpPath.relativize(home) File file = relativePath.toFile();

29 Wednesday, November 16, 11 File Operation – Copy, Move

• File copy is really easy – With fine grain control Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/copy_readme.txt”); Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); • File move is supported – Optional atomic move supported Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/readme.1st”); Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);

30 Wednesday, November 16, 11 Directories

• DirectoryStream iterate over entries – Scales to large directories – Uses less resources – Smooth out response time for remote file systems – Implements Iterable and Closeable for productivity • Filtering support – Build-in support for glob, regex and custom filters

Path srcPath = Paths.get(“/home/fred/src”); try (DirectoryStream dir = srcPath.newDirectoryStream(“*.java”)) { for (Path file: dir) System.out.println(file.getName()); }

31 Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Path searchDir = Paths.get("c:/Users"); final Path findFile = Paths.get("baby.jpg");

Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Path searchDir = Paths.get("c:/Users"); final Path findFile = Paths.get("baby.jpg"); FileVisitor visitor = new SimpleFileVisitor() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.getName().startsWith(findFile.getName()) ) { System.out.format("%s%n", findFile); } return FileVisitResult.CONTINUE; } };

Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Path searchDir = Paths.get("c:/Users"); final Path findFile = Paths.get("baby.jpg"); FileVisitor visitor = new SimpleFileVisitor() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.getName().startsWith(findFile.getName()) ) { System.out.format("%s%n", findFile); } return FileVisitResult.CONTINUE; } }; EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Path searchDir = Paths.get("c:/Users"); final Path findFile = Paths.get("baby.jpg"); FileVisitor visitor = new SimpleFileVisitor() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.getName().startsWith(findFile.getName()) ) { System.out.format("%s%n", findFile); } return FileVisitResult.CONTINUE; } }; EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(searchDir, opts, Integer.MAX_VALUE, visitor);

Wednesday, November 16, 11 Using NIO.2 APIs to search a directory

import java.nio.file.*;

Path searchDir = Paths.get("c:/Users"); final Path findFile = Paths.get("baby.jpg"); FileVisitor visitor = new SimpleFileVisitor() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.getName().startsWith(findFile.getName()) ) { System.out.format("%s%n", findFile); } return FileVisitResult.CONTINUE; } }; EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(searchDir, opts, Integer.MAX_VALUE, visitor);

Wednesday, November 16, 11 Java SE 7 Top 10

3. Fork/Join APIs

33 Wednesday, November 16, 11 Concurrency APIs

• JSR166y • Update to JSR166x which was an update to JSR166 • Adds a lightweight task framework • Also referred to as Fork/Join

34 Wednesday, November 16, 11 Fork Join Framework

• Goal is to take advantage of multiple processor • Designed for task that can be broken down into smaller pieces – Eg. Fibonacci number fib(10) = fib(9) + fib(8) • Typical algorithm that uses fork join

if the task is manageably small perform the task else fork task into x number of smaller/similar task join the results

35 Wednesday, November 16, 11 Concept of Fork/Join Framework

Wednesday, November 16, 11 Concept of Fork/Join Framework

Large, compute-intensive task

Wednesday, November 16, 11 Concept of Fork/Join Framework

Large, compute-intensive task

Fork into subtasks

Wednesday, November 16, 11 Concept of Fork/Join Framework

Large, compute-intensive task

Fork into subtasks Process tasks in parallel

Wednesday, November 16, 11 Concept of Fork/Join Framework

Large, compute-intensive task

Fork into Join subtasks as subtasks Process tasks they complete in parallel

Wednesday, November 16, 11 Concept of Fork/Join Framework

Large, compute-intensive Completed task task

Fork into Join subtasks as subtasks Process tasks they complete in parallel

Wednesday, November 16, 11 Key Classes

• ForkJoinPool – Executor service for running ForkJoinTask • ForkJoinTask – The base class for forkjoin task • RecursiveAction – A subclass of ForkJoinTask – A recursive resultless task – Implements compute() abstract method to perform calculation • RecursiveTask – Similar to RecursiveAction but returns a result

37 Wednesday, November 16, 11 Example: Blurring an image

public class ForkBlur { private int[] mSource; private int mStart; private int mLength; private int[] mDestination;

private int mBlurWidth = 15; // Processing window size, should be odd.

public ForkBlur(int[] src, int start, int length, int[] dst) { mSource = src; mStart = start; mLength = length; mDestination = dst; }

...

©2011 Oracle Corporation

Wednesday, November 16, 11 Example: Blurring an image

public class ForkBlur {

... // this is the heavy lifting protected void computeDirectly() { int sidePixels = (mBlurWidth - 1) / 2; for (int index = mStart; index < mStart + mLength; index++) { // Calculate average. float rt = 0, gt = 0, bt = 0; for (int mi = -sidePixels; mi <= sidePixels; mi++) { int mindex = Math.min(Math.max(mi + index, 0), mSource.length - 1); int pixel = mSource[mindex]; rt += (float)((pixel & 0x00ff0000) >> 16) / mBlurWidth; gt += (float)((pixel & 0x0000ff00) >> 8) / mBlurWidth; bt += (float)((pixel & 0x000000ff) >> 0) / mBlurWidth; }

// Re-assemble destination pixel. int dpixel = (0xff000000 ) | (((int)rt) << 16) | (((int)gt) << 8) | (((int)bt) << 0); mDestination[index] = dpixel; }

...

}

©2011 Oracle Corporation

Wednesday, November 16, 11 Heavy lifting in parallel using Fork/Join

public class ForkBlur extends RecursiveAction {

protected void compute() { // use the Fork/Join pattern here } ...

protected void computeDirectly() { // this is still the heavy lifting

}

...

}

©2011 Oracle Corporation

Wednesday, November 16, 11 Basic concept of Fork/Join

if the task is manageably small perform the task else fork task into x number of smaller/similar task join the results

©2011 Oracle Corporation

Wednesday, November 16, 11 Application of Fork/Join

protected static int sThreshold = 100000;

protected void compute() {

// is my portion of the work is small enough ? if (mLength < sThreshold) {

// just do it computeDirectly(); return; } else {

// split my work into two pieces int split = mLength / 2;

invokeAll( new ForkBlur(mSource, mStart, split, mDestination), new ForkBlur(mSource, mStart + split, mLength - split, mDestination) );

} }

©2011 Oracle Corporation

Wednesday, November 16, 11 Running the code

// source image pixels are in src // destination image pixels are in dst ForkBlur fb = new ForkBlur(src, 0, src.length, dst);

ForkJoinPool pool = new ForkJoinPool();

// now the work can be executed in parallel pool.invoke(fb);

©2011 Oracle Corporation

Wednesday, November 16, 11 Java SE 7 Top 10

4. Java on the desktop

44 Wednesday, November 16, 11 Client Libraries

• Nimbus Look and Feel • Platform APIs for shaped and translucent windows • JLayer (formerly from Swing labs) • Optimised 2D rendering

45 Wednesday, November 16, 11 Nimbus Look and Feel

• Better than Metal for cross platform look-and-feel • Introduced in Java SE 6u10, now part of Swing • Not the default L&F

46 Wednesday, November 16, 11 JLayer component Easy enrichment for Swing components

47 Wednesday, November 16, 11 JLayer component The universal decorator

• Transparent decorator for a Swing component • Controls the painting of its subcomponents • Catches all input and focus events for the whole hierarchy

// wrap your component with JLayer JLayer layer = new JLayer(myPanel);

// custom ui provides all extra functionality layer.setUI(myCustomLayerUI);

// add the layer as usual component frame.add(layer);

48 Wednesday, November 16, 11 Java SE 7 Top 10

5. DaVinci Machine

49 Wednesday, November 16, 11 Languages Like Virtual Machines

• Programming languages need runtime support • Memory management / Garbage collection • Concurrency control • Security • Reflection • Debugging integration • Standard libraries • Compiler writers have to build these from scratch • Targeting a VM allows reuse of infrastructure

50 Wednesday, November 16, 11 JVM Specification

“The Java virtual machine knows nothing about the Java programming language, only of a particular binary format, the class file format.”

1.2 The Java Virtual Machine Spec.

51 Wednesday, November 16, 11 Languages Running on the JVM

Tea Zigzag JESS Jickle iScript Modula-2 CAL Lisp JavaScript Correlate Nice JudoScript Simkin Drools Basic Eiffel Icon Groovy v-language Prolog Mini Pascal Luck Tcl PLAN Hojo Rexx Scala JavaFX Script Funnel Tiger Anvil Yassl OberonFScript E Smalltalk Logo Tiger JHCR JRuby Ada G Scheme Clojure Phobos Processing WebL Dawn SleepSather LLP TermWare Pnuts Bex Script BeanShell Forth C# PHP SALSA ObjectScript Jython Yoix Piccola

52 Wednesday, November 16, 11 InvokeDynamic Bytecode

• JVM currently has four ways to invoke method • Invokevirtual, invokeinterface, invokestatic, invokespecial • All require full method signature data • InvokeDynamic will use method handle • Effectively an indirect pointer to the method • When dynamic method is first called bootstrap code determines method and creates handle • Subsequent calls simply reference defined handle • Type changes force a re-compute of the method location and an update to the handle • Method call changes are invisible to calling code

53 Wednesday, November 16, 11 CallSite and MethodHandle

• invokedynamic linked to a CallSite – CallSite can be linked or unlinked – CallSite holder of MethodHandle • MethodHandle is a directly executable reference to an underlying method, constructor, field – Can transform arguments and return type – Transformation – conversion, insertion, deletion, substitution

54 Wednesday, November 16, 11 Java SE 7 Top 10

6. New Garbage collector

55 Wednesday, November 16, 11 VM: Updates to Experimental GC – G1

• Garbage First - “G1” intended to replace* Concurrent Mark-Sweep (CMS) in Hotspot at some future release • G1 is included for experimentation in Java 7 • Key benefits: • More predictably “soft real-time” – temporal configuration • High throughput • Basics: • Heap partitioned into equal-sized heap regions • Compacts as it proceeds – looks for regions with no live objects for immediate reclamation

*not an official fwd looking statement

56 Wednesday, November 16, 11 Java SE 7 Top 10

7. JVM Convergence

57 Wednesday, November 16, 11 JVM Convergence – Forward looking Project “HotRockit”

JDK 7 GA – 07/11 JDK 7u2 JDK 7uX JDK 8 GA

• Hotspot 21 • Hotspot 22 • Hotspot 23 • Hotspot24 • Java SE 7 Support • Performance • More performance • Java SE 8 Support • Rebranding • Enable large heaps • Improved command • All performance with reasonable line servicability features from • Improved JMX latencies (jcmd) JRockit ported Agent • Enable large heaps • All servicability • Command line servicability tool with consistent features from (jrcmd) reasonable latencies JRockit ported • No PermGen • Compiler controls • Verbose logging --- Premium ------Premium ------Premium --- • Complete JRockit • JRockit Mission • Improved JRockit Flight Recorder Control Memleak Mission Control Support Tool Support Console support • Soft Real Time GC

Wednesday, November 16, 11 Java SE 7 Top 10

8. More timely MAC port

59 Wednesday, November 16, 11 JDK 7 Platform Support

• Windows x86 • Server 2008, Server 2008 R2, 7 & 8 (when it GAs) • Windows Vista, XP • x86 • Oracle Linux 5.5+, 6.x • Red Hat Enterprise Linux 5.5+, 6.x • SuSE Linux Enterprise Server 10.x, 11.x • Ubuntu Linux 10.04 LTS, 11.04 • Solaris x86/SPARC • Solaris 10.9+, 11.x • Apple OSX x86 • will be supported post-GA, soon

Note: JDK 7 should run on pretty much any Windows/Linux/Solaris. These configurations are the ones primarily tested by Oracle, and for which we provide commercial support.

60 Wednesday, November 16, 11 Java SE 7 Top 10

9. Updated JavaDoc

61 Wednesday, November 16, 11 JavaDoc Improvements in Java 7

• Section 508 accessibility guidelines • Captions, headings, etc. • Previously, JavaDoc wrote to an OutputStream on the fly meaning it built the document sequentially, imposing limitations • Now uses internal “HTMLTree” classes • Generates compliant HTML • Allows for more advancements in the future • Removes limitation of only being able to execute only once in any VM • Was fine when used as a command line tool • Continuous build, etc, made it necessary to address this!

62 Wednesday, November 16, 11 CSS for JavaDoc - stylesheet.css

63 Wednesday, November 16, 11 Java SE 7 Top 10

10. Many more smaller improvements

64 Wednesday, November 16, 11 Miscellaneous Things

• Security • Eliptic curve cryptography • TLS 1.2 • JAXP 1.4.4 • JAX-WS 2.2 • JAXB 2.2 • ClassLoader architecture changes • close() for URLClassLoader

65 Wednesday, November 16, 11 Top 10

• Project Coin • Nio 2 • Fork/ Join APIs • Desktop APIs • DaVinci Machine • New garbage collector • JVM Convergence • More timely MAC ports • Improved JavaDoc • Many more smaller features

66 Wednesday, November 16, 11 67 Wednesday, November 16, 11