SlideShare a Scribd company logo
Back to the Future
with Java 7
Martijn Verburg
(@karianna, @java7developer)

http://www.java7developer.com

                                Slide Design by http://www.kerrykenneally.com
                                                           1
Who is this guy anyway?




                          2
Who is this guy anyway?
http://www.meetup.com/Londonjavacommunity/




                                             3
Who is this guy anyway?




                          4
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
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
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
Along came Larry...




                      8
                      9
Parting of ways / new joiners




                                                9
                                Original Image by Acaben
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
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
Project Coin - Highlights

• Strings in switch

• try-with-resources (aka ARM or TWR)

• Enhanced syntax for numeric literals

• Diamond Syntax




                                         12
Strings in switch

public 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
try-with-resources

// Some exception handling omitted,
// bonus points for guessing the right one!
URL url =
  new URL("http://www.java7developer.com/blog/?page_id=97");
try (InputStream in = url.openStream())
{
  Files.copy(in, Paths.get("output.txt"));
}
catch(IOException ex)
{
  ex.printStackTrace();
}




                                                          14
Enhanced numeric literals

int x = 0b1100110;


byte allOnes = 255y; // (byte)0xFF or -1 in Java 6

long anotherLong = 2_147_483_648L;


// Help for bit-twiddlers
int bitPattern = 0b0001_1100__0011_0111__0010_1011__1010_0011;




                                                          15
Diamond syntax

Map<Integer, Map<String, String>> usersLists =
  new HashMap<Integer, Map<String, String>>();


// Wouldn't 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
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
URLStream to file - Java 6 style

URL url =
  new URL("http://www.java7developer.com/blog/?page_id=97");
try (
  FileOutputStream fos =
    new FileOutputStream(new File("output.txt"));
  InputStream is = url.openStream() )
{
  byte[] buf = new byte[4096];
  int len;
  while ((len = is.read(buf)) > 0)
  {
    fos.write(buf, 0, len);
  }
} catch (IOException e)
{
  e.printStackTrace();
}
                                                          18
URL stream to file in Java 7


URL url =
  new URL("http://www.java7developer.com/blog/?page_id=97");
try (InputStream in = url.openStream())
{
  Files.copy(in, Paths.get("output.txt"));
}
catch(IOException ex)
{
  ex.printStackTrace();
}




                                                          19
NIO.2 - Future base file I/O

try
{
  Path file = Paths.get("/usr/karianna/foobar.txt");
  AsynchronousFileChannel channel =
    AsynchronousFileChannel.open(file);
  ByteBuffer buffer = ByteBuffer.allocate(100_000);
  Future<Integer> result = channel.read(buffer, 0);
  while(!result.isDone())
  {
    System.out.println("Pretend Business Process");
  }
  Integer bytesRead = result.get();
}
catch (IOException | ExecutionException | InterruptedException e)
{
  e.printStackTrace();
}
                                                          20
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
Example - ThreadPoolManager

private 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
Cancelling using Reflection

// .... in ThreadPoolManager
public 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
Cancelling using a Proxy

// .... in ThreadPoolManager
public static class CancelProxy {

    private CancelProxy() { }

    public void invoke(ThreadPoolManager manager,
                       ScheduledFuture<?> handle)
    {
      manager.cancel(handle);
    }
}


public CancelProxy makeProxy() {
  return new CancelProxy();
}




                                                    24
Cancelling using MethodHandle

// .... in ThreadPoolManager
public 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
MethodHandle Contrasted

              Reflection             Proxies                  MethodHandle


Access        Must use               Inner classes can        Full access to all
              setAccessible().       access restricted        methods allowed from
Control                              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 consume
Discipline                           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
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
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
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
Concurrency matters again
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
Fork/Join - compute

@Override
protected 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
Fork/Join - merge

private 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
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
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
Java isn’t just the language, it’s the ecosystem




                                         36
And it’s about the community innit!




                                      37
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
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 Parleys.com videos of him online




                                                            39
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 “ME.next”

• 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
Google vs. Oracle - Round 1!




                               41
Where’s the lawsuit at?

• http://www.groklaw.net (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
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
JCP - Trouble in paradise?

• OK, so it was never _really_ paradise

• Stephen Colebourne’s blog captured some of the events
   – http://www.jroller.com/scolebourne/


• 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
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
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
Thanks for listening!
        (http://www.java7developer.com)




• Martijn Verburg - @karianna
• Slides at slideshare.com
                                          47

More Related Content

PDF
Fast as C: How to Write Really Terrible Java
PPTX
Jdk(java) 7 - 6 기타기능
PPTX
Jdk 7 4-forkjoin
PDF
Bytecode manipulation with Javassist and ASM
PPTX
Jersey framework
PPTX
The Art of JVM Profiling
PPTX
Pure Java RAD and Scaffolding Tools Race
Fast as C: How to Write Really Terrible Java
Jdk(java) 7 - 6 기타기능
Jdk 7 4-forkjoin
Bytecode manipulation with Javassist and ASM
Jersey framework
The Art of JVM Profiling
Pure Java RAD and Scaffolding Tools Race

What's hot (20)

PDF
JVM for Dummies - OSCON 2011
PDF
Highlights from Java 10, 11 and 12 and Future of Java at JUG Koblenz
PPTX
Java Bytecode For Discriminating Developers - GeeCON 2011
PPTX
모던자바의 역습
PDF
JRuby and You
PDF
Everything you wanted to know about Stack Traces and Heap Dumps
PDF
Beyond JVM - YOW! Sydney 2013
ODP
Java 7: Quo vadis?
PDF
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
PDF
Java Bytecode for Discriminating Developers - JavaZone 2011
PPTX
KEY
JavaOne 2011 - JVM Bytecode for Dummies
ZIP
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
PPTX
Do we need Unsafe in Java?
PDF
JRuby and Invokedynamic - Japan JUG 2015
PDF
GeeCON 2017 - TestContainers. Integration testing without the hassle
PDF
Using Java from Ruby with JRuby IRB
PPT
Building a java tracer
PPTX
Use of Apache Commons and Utilities
PDF
Groovy And Grails JUG Trento
JVM for Dummies - OSCON 2011
Highlights from Java 10, 11 and 12 and Future of Java at JUG Koblenz
Java Bytecode For Discriminating Developers - GeeCON 2011
모던자바의 역습
JRuby and You
Everything you wanted to know about Stack Traces and Heap Dumps
Beyond JVM - YOW! Sydney 2013
Java 7: Quo vadis?
Jenkins 2を使った究極のpipeline ~ 明日もう一度来てください、本物のpipelineをお見せしますよ ~
Java Bytecode for Discriminating Developers - JavaZone 2011
JavaOne 2011 - JVM Bytecode for Dummies
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Do we need Unsafe in Java?
JRuby and Invokedynamic - Japan JUG 2015
GeeCON 2017 - TestContainers. Integration testing without the hassle
Using Java from Ruby with JRuby IRB
Building a java tracer
Use of Apache Commons and Utilities
Groovy And Grails JUG Trento
Ad

Viewers also liked (13)

KEY
Polyglot and functional (Devoxx Nov/2011)
KEY
Modern Java Concurrency (Devoxx Nov/2011)
KEY
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
PDF
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
KEY
Introduction to Java 7 (OSCON 2012)
KEY
Free community with deep roots
PDF
Introduction to Java 7 (Devoxx Nov/2011)
PPT
Java 7 - short intro to NIO.2
KEY
Polyglot and Functional Programming (OSCON 2012)
PDF
Garbage Collection - The Useful Parts
PDF
NoHR Hiring
KEY
Modern software development anti patterns (OSCON 2012)
KEY
Modern Java Concurrency (OSCON 2012)
Polyglot and functional (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
Introduction to Java 7 (OSCON 2012)
Free community with deep roots
Introduction to Java 7 (Devoxx Nov/2011)
Java 7 - short intro to NIO.2
Polyglot and Functional Programming (OSCON 2012)
Garbage Collection - The Useful Parts
NoHR Hiring
Modern software development anti patterns (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
Ad

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

PDF
What to expect from Java 9
PPTX
Java 7 Whats New(), Whats Next() from Oredev
PDF
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
PDF
55 new things in Java 7 - Devoxx France
PPTX
PDF
Java Future S Ritter
PPTX
Modern_Java_Workshop manjunath np hj slave
PPT
55 New Features in Java 7
PPTX
DevNexus 2020: Discover Modern Java
ODT
Best Of Jdk 7
PDF
Terence Barr - jdk7+8 - 24mai2011
PDF
Atlassian Groovy Plugins
PDF
Java features. Java 8, 9, 10, 11
PDF
Java >= 9
PPTX
Java 7 & 8 New Features
PDF
What`s new in Java 7
PDF
Inside the JVM - Follow the white rabbit!
PDF
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
PDF
Oscon Java Testing on the Fast Lane
PDF
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
What to expect from Java 9
Java 7 Whats New(), Whats Next() from Oredev
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
55 new things in Java 7 - Devoxx France
Java Future S Ritter
Modern_Java_Workshop manjunath np hj slave
55 New Features in Java 7
DevNexus 2020: Discover Modern Java
Best Of Jdk 7
Terence Barr - jdk7+8 - 24mai2011
Atlassian Groovy Plugins
Java features. Java 8, 9, 10, 11
Java >= 9
Java 7 & 8 New Features
What`s new in Java 7
Inside the JVM - Follow the white rabbit!
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
Oscon Java Testing on the Fast Lane
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PDF
Mushroom cultivation and it's methods.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
A Presentation on Artificial Intelligence
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Empathic Computing: Creating Shared Understanding
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
1. Introduction to Computer Programming.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Tartificialntelligence_presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Encapsulation theory and applications.pdf
Spectroscopy.pptx food analysis technology
Mushroom cultivation and it's methods.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Encapsulation_ Review paper, used for researhc scholars
A Presentation on Artificial Intelligence
Reach Out and Touch Someone: Haptics and Empathic Computing
Empathic Computing: Creating Shared Understanding
Assigned Numbers - 2025 - Bluetooth® Document
1. Introduction to Computer Programming.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Programs and apps: productivity, graphics, security and other tools
A comparative analysis of optical character recognition models for extracting...
Getting Started with Data Integration: FME Form 101
Tartificialntelligence_presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Spectral efficient network and resource selection model in 5G networks
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
OMC Textile Division Presentation 2021.pptx
Encapsulation theory and applications.pdf

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

  • 1. Back to the Future with Java 7 Martijn Verburg (@karianna, @java7developer) http://www.java7developer.com Slide Design by http://www.kerrykenneally.com 1
  • 2. Who is this guy anyway? 2
  • 3. Who is this guy anyway? http://www.meetup.com/Londonjavacommunity/ 3
  • 4. Who is this guy anyway? 4
  • 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. 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. 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
  • 9. Parting of ways / new joiners 9 Original Image by Acaben
  • 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. 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. Project Coin - Highlights • Strings in switch • try-with-resources (aka ARM or TWR) • Enhanced syntax for numeric literals • Diamond Syntax 12
  • 13. Strings in switch public 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. try-with-resources // Some exception handling omitted, // bonus points for guessing the right one! URL url = new URL("http://www.java7developer.com/blog/?page_id=97"); try (InputStream in = url.openStream()) { Files.copy(in, Paths.get("output.txt")); } catch(IOException ex) { ex.printStackTrace(); } 14
  • 15. Enhanced numeric literals int x = 0b1100110; byte allOnes = 255y; // (byte)0xFF or -1 in Java 6 long anotherLong = 2_147_483_648L; // Help for bit-twiddlers int bitPattern = 0b0001_1100__0011_0111__0010_1011__1010_0011; 15
  • 16. Diamond syntax Map<Integer, Map<String, String>> usersLists = new HashMap<Integer, Map<String, String>>(); // Wouldn't 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. 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. URLStream to file - Java 6 style URL url = new URL("http://www.java7developer.com/blog/?page_id=97"); try ( FileOutputStream fos = new FileOutputStream(new File("output.txt")); InputStream is = url.openStream() ) { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { fos.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } 18
  • 19. URL stream to file in Java 7 URL url = new URL("http://www.java7developer.com/blog/?page_id=97"); try (InputStream in = url.openStream()) { Files.copy(in, Paths.get("output.txt")); } catch(IOException ex) { ex.printStackTrace(); } 19
  • 20. NIO.2 - Future base file I/O try { Path file = Paths.get("/usr/karianna/foobar.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); ByteBuffer buffer = ByteBuffer.allocate(100_000); Future<Integer> result = channel.read(buffer, 0); while(!result.isDone()) { System.out.println("Pretend Business Process"); } Integer bytesRead = result.get(); } catch (IOException | ExecutionException | InterruptedException e) { e.printStackTrace(); } 20
  • 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. Example - ThreadPoolManager private 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. Cancelling using Reflection // .... in ThreadPoolManager public 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. Cancelling using a Proxy // .... in ThreadPoolManager public static class CancelProxy { private CancelProxy() { } public void invoke(ThreadPoolManager manager, ScheduledFuture<?> handle) { manager.cancel(handle); } } public CancelProxy makeProxy() { return new CancelProxy(); } 24
  • 25. Cancelling using MethodHandle // .... in ThreadPoolManager public 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. MethodHandle Contrasted Reflection Proxies MethodHandle Access Must use Inner classes can Full access to all setAccessible(). access restricted methods allowed from Control 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 consume Discipline 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. 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. 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. 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
  • 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. Fork/Join - compute @Override protected 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. Fork/Join - merge private 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. 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. 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. Java isn’t just the language, it’s the ecosystem 36
  • 37. And it’s about the community innit! 37
  • 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. 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 Parleys.com videos of him online 39
  • 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 “ME.next” • 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. Google vs. Oracle - Round 1! 41
  • 42. Where’s the lawsuit at? • http://www.groklaw.net (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. 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. JCP - Trouble in paradise? • OK, so it was never _really_ paradise • Stephen Colebourne’s blog captured some of the events – http://www.jroller.com/scolebourne/ • 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. 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. 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. Thanks for listening! (http://www.java7developer.com) • Martijn Verburg - @karianna • Slides at slideshare.com 47

Editor's Notes

  • #2: \n
  • #3: \n
  • #4: \n
  • #5: How this talk is gonna work\n
  • #6: Java&amp;#x2019;s not dead - it&amp;#x2019;s just been resting!\n
  • #7: How di I get here? Where are my shoes?\n
  • #8: Along came Larry...\n
  • #9: Parting of ways and new Joiners\n
  • #10: OpenJDK - Plan B\n
  • #11: Project Coin\n
  • #12: Project Coin - highlights\n
  • #13: Strings in switch\n
  • #14: try-with-resources\n
  • #15: enhanced numeric literals\n
  • #16: diamond syntax\n
  • #17: NIO.2\n
  • #18: URLStream to file in Java 6\n
  • #19: URLStream to file in Java 7\n
  • #20: Future based Asynch I/O\n
  • #21: method handles\n
  • #22: URLStream to file in Java 6\n
  • #23: Example of using reflection to cancel\n
  • #24: Example of using a proxy to cancel\n
  • #25: Example of using a MethodHandle to cancel\n
  • #26: MethodHandles compared and contrasted\n
  • #27: invokedynamic\n
  • #28: A friend to dynamic languages\n
  • #29: Concurrency\n
  • #30: Concurrency matters again\n
  • #31: Fork/Join\n
  • #32: compute code\n
  • #33: merge code\n
  • #34: DEMO then New concurrency models\n
  • #35: What&amp;#x2019;s in my future?\n
  • #36: \n
  • #37: \n
  • #38: \n
  • #39: \n
  • #40: \n
  • #41: \n
  • #42: \n
  • #43: \n
  • #44: \n
  • #45: \n
  • #46: \n
  • #47: \n
  • #48: \n