Back to the future with Java 7 (Geekout June/2011)


Published on

A talk on Java 7 - a few weeks before it came out.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • How this talk is gonna work\n
  • Java’s not dead - it’s just been resting!\n
  • How di I get here? Where are my shoes?\n
  • Along came Larry...\n
  • Parting of ways and new Joiners\n
  • OpenJDK - Plan B\n
  • Project Coin\n
  • Project Coin - highlights\n
  • Strings in switch\n
  • try-with-resources\n
  • enhanced numeric literals\n
  • diamond syntax\n
  • NIO.2\n
  • URLStream to file in Java 6\n
  • URLStream to file in Java 7\n
  • Future based Asynch I/O\n
  • method handles\n
  • URLStream to file in Java 6\n
  • Example of using reflection to cancel\n
  • Example of using a proxy to cancel\n
  • Example of using a MethodHandle to cancel\n
  • MethodHandles compared and contrasted\n
  • invokedynamic\n
  • A friend to dynamic languages\n
  • Concurrency\n
  • Concurrency matters again\n
  • Fork/Join\n
  • compute code\n
  • merge code\n
  • DEMO then New concurrency models\n
  • What’s in my future?\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Back to the future with Java 7 (Geekout June/2011)

    1. 1. Back to the Futurewith Java 7Martijn Verburg(@karianna, @java7developer) Slide Design by 1
    2. 2. Who is this guy anyway? 2
    3. 3. Who is this guy anyway? 3
    4. 4. Who is this guy anyway? 4
    5. 5. How this talk is gonna work• This is a fact! – This is an opinion• Where’s Marty McFly? – Tough luck.• I will not make jokes about Estonia, Skype or the recent football results• This talk may be a little different to advertised... – Due to time constraints, other talks and beer 5
    6. 6. Java’s not dead, it’s just been resting!• It’s quite true that Java (the language) has been a bit quiet – But that’s a lot to do with the “big company” stuff that we’ve heard about• Java 6 had some significant improvements – Performance is a key benefit• Java 7 sometimes seemed to be lost in the wilderness – Some of the features were released as updates to SE 6 – *Big* arguments about some features.... – JCP troubles 6
    7. 7. How did we get here? Where are my shoes?• The community and the platform have not been quiet – You’re a noisy bunch, that’s for sure! – Conference attendances are _way_ up and growing – Oracle marketing estimates 9-10 million developers – Dozens of new JVM languages• We’re moving again – OpenJDK is liberated (GPL) – Like any good democracy, we need to be vigilant of our freedoms – JCP deadlock needed to be broken 7
    8. 8. Along came Larry... 8 9
    9. 9. Parting of ways / new joiners 9 Original Image by Acaben
    10. 10. OpenJDK - Plan B• 20 Sep 2010 - Mark Reinhold announces Plan B – Splits OpenJDK effort into Java 7 (July 2011) and Java 8 (2012) – Popular choice with the community• Some JRockit features to be added to OpenJDK – Enhanced mgmt of the JVM – Exact roadmap not yet clear• Changes to the memory model – Bye-bye Permgen - *almost*• Some new features to be delayed until JDK 8 – Closures Lambdas SAM literals – Modularisation (aka Jigsaw) 10
    11. 11. Project Coin• “Small” changes• Language Level, not VM• Stay away from the type system• Developed in a very OSS manner – From idea inception through to development – Initial ideas must come with a strawman prototype – Was an ‘interesting’ experience for all involved – Looks likely to be repeated for JDK 8 small features 11
    12. 12. Project Coin - Highlights• Strings in switch• try-with-resources (aka ARM or TWR)• Enhanced syntax for numeric literals• Diamond Syntax 12
    13. 13. Strings in switchpublic void printDay(String dayOfWeek) { switch (dayOfWeek) { case "Sunday": System.out.println("Dimanche"); break; case "Monday": System.out.println("Lundi"); break; case "Tuesday": System.out.println("Mardi"); break; case "Wednesday": System.out.println("Mercredi"); break; case "Thursday": System.out.println("Jeudi"); break; case "Friday": System.out.println("Vendredi"); break; case "Saturday": System.out.println("Samedi"); break; default: System.out.println("Error: [" + dayOfWeek + "] is not a day of the week"); break; }} 13
    14. 14. try-with-resources// Some exception handling omitted,// bonus points for guessing the right one!URL url = new URL("");try (InputStream in = url.openStream()){ Files.copy(in, Paths.get("output.txt"));}catch(IOException ex){ ex.printStackTrace();} 14
    15. 15. Enhanced numeric literalsint x = 0b1100110;byte allOnes = 255y; // (byte)0xFF or -1 in Java 6long anotherLong = 2_147_483_648L;// Help for bit-twiddlersint bitPattern = 0b0001_1100__0011_0111__0010_1011__1010_0011; 15
    16. 16. Diamond syntaxMap<Integer, Map<String, String>> usersLists = new HashMap<Integer, Map<String, String>>();// Wouldnt it be better if we could just write something like:Map<Integer, Map<String, String>> usersLists = new HashMap<>();// This is actually true type inference, not string substitution/* * .NET and Scala type infer on variables * Java’s diamond syntax type infers on values */ 16
    17. 17. NIO.2 - New I/O version 2• Is aimed at simplifying I/O in Java• A new file system and path abstraction – Based on Path – Bulk access to file attributes – File system specific support (e.g. Symbolic links)• Asynchronous (non-blocking) I/O – For sockets and files – Mainly utilises java.util.concurrent.Future• Socket/Channel construct – Binding, options and multicast 13
    18. 18. URLStream to file - Java 6 styleURL url = new URL("");try ( FileOutputStream fos = new FileOutputStream(new File("output.txt")); InputStream is = url.openStream() ){ byte[] buf = new byte[4096]; int len; while ((len = > 0) { fos.write(buf, 0, len); }} catch (IOException e){ e.printStackTrace();} 18
    19. 19. URL stream to file in Java 7URL url = new URL("");try (InputStream in = url.openStream()){ Files.copy(in, Paths.get("output.txt"));}catch(IOException ex){ ex.printStackTrace();} 19
    20. 20. NIO.2 - Future base file I/Otry{ Path file = Paths.get("/usr/karianna/foobar.txt"); AsynchronousFileChannel channel =; ByteBuffer buffer = ByteBuffer.allocate(100_000); Future<Integer> result =, 0); while(!result.isDone()) { System.out.println("Pretend Business Process"); } Integer bytesRead = result.get();}catch (IOException | ExecutionException | InterruptedException e){ e.printStackTrace();} 20
    21. 21. NIO.2 - New I/O version 2• Come in as part of invokedynamic• Runtime Currently we have observation with Reflection API – See interfaces/classes/methods and fields at runtime • Without knowing their names at compile time• JDK 7 introduces a new way to inspect at runtime• Method Handles – Implement a subclass of java.lang.invoke.MethodHandle – Are objects that represent the ability to call a method • More powerful than Callables• May the presenter gods be kind.... 13
    22. 22. Example - ThreadPoolManagerprivate final ScheduledExecutorService stpe = Executors.newScheduledThreadPool(2);private final BlockingQueue<WorkUnit<String>> lbq;public ScheduledFuture<?> run(QueueReaderTask msgReader) { msgReader.setQueue(lbq); return stpe.scheduleAtFixedRate(msgReader, 10, 10, TimeUnit.MILLISECONDS);}private void cancel(final ScheduledFuture<?> handle) { stpe.schedule(new Runnable() { public void run() { handle.cancel(true); } }, 10, TimeUnit.MILLISECONDS);} 22
    23. 23. Cancelling using Reflection// .... in ThreadPoolManagerpublic Method makeMethod() { Method method = null; try { Class<?>[] argTypes = new Class[] { ScheduledFuture.class }; method = ThreadPoolManager.class.getDeclaredMethod("cancel", argTypes); method.setAccessible(true); } catch (IllegalArgumentException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return meth;} 23
    24. 24. Cancelling using a Proxy// .... in ThreadPoolManagerpublic static class CancelProxy { private CancelProxy() { } public void invoke(ThreadPoolManager manager, ScheduledFuture<?> handle) { manager.cancel(handle); }}public CancelProxy makeProxy() { return new CancelProxy();} 24
    25. 25. Cancelling using MethodHandle// .... in ThreadPoolManagerpublic MethodHandle makeMh() { MethodHandle methodHandle; // MethodType.methodType encodes return type & args MethodType methodType = MethodType.methodType(void.class, ScheduledFuture.class); try { methodHandle = MethodHandles.lookup().findVirtual (ThreadPoolManager.class, "cancel", methodType); } catch (NoAccessException e) { throw (AssertionError)new AssertionError().initCause(e); } return methodHandle;} 25
    26. 26. MethodHandle Contrasted Reflection Proxies MethodHandleAccess Must use Inner classes can Full access to all setAccessible(). access restricted methods allowed fromControl methods. context. No issue with Can be disallowed by security manager. security managers.Type None. Ugly exception Static. Can be too Typesafe at run-time. on mismatch. strict. May need a lot Does not consumeDiscipline of permgen for all permgen. proxies.Performance Slow compared to Fast as any other Aiming to be as fast alternatives. method call. as other method calls. 26
    27. 27. InvokeDynamic• invokedynamic is a key new JVM feature – It’s the first new bytecode since Java 1.0 – Joins invokevirtual, invokestatic, invokeinterface and invokespecial• It removes a key part of the static typing system – Method names / signatures will not need to be known at compile time – User code can determine dispatch at runtime (uses MethodHandle)• Aims to be as fast as invokevirtual• No Java syntax for handling it in Java 7 - but maybe for 8 27
    28. 28. A friend to dynamic languages• Free, open JVM languages such as JRuby, Jython, Groovy, Clojure et al all stand to benefit from invokedynamic – These gains will vary, JRuby gains a lot, Clojure not so much – They’re even bringing it to Scala!• Groovy is already well established as Java’s flexible friend – Increasing its performance keeps it at the forefront• JRuby has been working closely with the JSR-292 team – Big potential wins – Makes JRuby enticing to Ruby developers 28
    29. 29. And now for something completely different - Concurrency• Threads are like Otters!• Collaborative• Competitive• Sneaky• Hare off in different directions• Can wreak havoc if not contained 29
    30. 30. Concurrency matters again
    31. 31. Fork/Join• Java 7 gets in on the concurrency party with F/J – similar to MapReduce – useful for a certain class of problems – fork and join executions are not necessarily threads• In our example, we subclass RecursiveAction• Need to override compute() method• Framework provides – an invokeAll() to hand off more tasks – Dynamic thread pool – Work Queues, inc. Work stealing 31
    32. 32. Fork/Join - compute@Overrideprotected void compute() { if (size() < SMALL_ENOUGH) { System.arraycopy(updates, start, result, 0, size()); Arrays.sort(result, 0, size()); } else { int mid = size() / 2; BlogUpdateSorter left = new BlogUpdateSorter (updates, start, start + mid); BlogUpdateSorter right = new BlogUpdateSorter (updates, start + mid, end); // NB: This is a synchronous call invokeAll(left, right); merge(left, right); }} 32
    33. 33. Fork/Join - mergeprivate void merge(BlogUpdateSorter left, BlogUpdateSorter right) { int i, lCt, rCt = 0; while (lCt < left.size() && rCt < right.size()) { result[i++] = (left.result[lCt].compareTo(right.result[rCt]) < 0) ? left.result[lCt++] : right.result[rCt++]; } while (lCt < left.size()) result[i++] = left.result[lCt++]; while (rCt < right.size()) result[i++] = right.result[rCt++];}public int size() { return end - start; }public Update[] getResult() { return result; } 33
    34. 34. New concurrency models• Java’s approach of mutable state, locks and visible by default looks increasingly dated – java.util.concurrent is a big help, but can only go so far – Java’s syntax and semantics are constraints – Thread is not a high-level concurrency abstraction• Other languages on the JVM are free to innovate – Scala • Powerful actors model – Clojure • Immutable by default • Thread-isolation by default • STM subsystem • Multiple concurrency models 34
    35. 35. What’s in my future?• Learning another JVM language won’t hurt! – Lots to choose from – No “Java Killer” yet.....• Don’t forget about Java 7! – Some compelling new features (Coin, NIO.2, F/J, etc) – Yet more performance• The Multi-core revolution is here – Brush up your modern concurrency – Java 7 makes this easier – Other languages offer alternative approaches 35
    36. 36. Java isn’t just the language, it’s the ecosystem 36
    37. 37. And it’s about the community innit! 37
    38. 38. Future of Java SE• Will be just fine• The mainline VM will continue to improve – invokedynamic – JRockit feature merge – Typed values? Structs for HPC?• Probably not too many faddish language features – But you can have what you want anyway in other JVM languages – Yeah, we’re looking at you Scala, Clojure, Groovy fans 38
    39. 39. Future of JEE• The future here looks bright! – More servers have become JEE6 certified – JEE7 process is starting to get underway – RESTFul and cloud at the forefront• JEE has shrunk whilst the alternatives have grown – They’re pretty much meeting in the middle – Spring is quite big these days...• Case Study - Adam Bien (Java Champion) – Live Demo - rapid development of apps with core JEE6 • Check out the videos of him online 39
    40. 40. Future of Java ME• On the decline? – Nokia has dropped it from their technology roadmap – ME still popular in the “dumbphone” market • That’s still a really huge market• Oracle are working on “”• Could Java SE eventually run on mobiles? – Maybe after JDK 8?• Could Android become the official replacement for Java ME? – “No Comment” (Oracle and Google) – Seems unlikely today, but stranger things have happened 40
    41. 41. Google vs. Oracle - Round 1! 41
    42. 42. Where’s the lawsuit at?• (search for Oracle Google)• Most recent case event: #patents relevant reduced - maybe – Won’t hear any more significant news for another few months• Developer community at Devoxx ‘10 voted (87%) that the lawsuit was harmful in some way to Java – Repeated surveys get similar results• The message that this is scaring off the community & corporate customers is getting through to Oracle Mgmt – We’ve seen improvements 42
    43. 43. Java FX• Well, v1.0 was a nice try – Did anyone really want JavaFX Script?• Java FX 2.0 is coming – Refocus around Java and other JVM languages – Does a Java client even matter anymore? – Can it shake off the FX Script legacy?• MSFT are downgrading Silverlight from their roadmap – ‘HTML5’ seems to be the way forward• Why have another runtime in a browser when it already has a capable VM (i.e. JavaScript)? 43
    44. 44. JCP - Trouble in paradise?• OK, so it was never _really_ paradise• Stephen Colebourne’s blog captured some of the events –• Prominent members left – Doug Lea, “Crazy” Bob Lee• Community members Werner Keil, LJC and SouJava have joined – Hopefully can work with Oracle et al on positive changes – Starting with JSR 348 – Now is a good time to make your voice heard! 44
    45. 45. OpenJDK governance?• Was there a mature OSS gov. model for OpenJDK?• Surely something is better than nothing• New attempt being made by Mark Reinhold & the committee – Really positive that the team are trying to make progress – Open mailing list: .... Doug Lea is back – Still an awful lot to be ironed out - but possibilities – Burden’s still on Oracle to engage with the community – But the community need to step up as well 45
    46. 46. The future’s bright. The future’s Java!• We have arguably the most capable VM on the planet• We have a wealth of new languages to complement and challenge Java (and Java 7 of course)!• We have oceans of open source software• We have a great community (you guys)!!• Opportunity to engage & utilise our “Interesting Times”• It’s a GREAT time to be working in the Java ecosystem 46
    47. 47. Thanks for listening! (• Martijn Verburg - @karianna• Slides at 47