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
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
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
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
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
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
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
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
Notas del editor
\n
\n
\n
How this talk is gonna work\n
Java&#x2019;s not dead - it&#x2019;s just been resting!\n