What’s new in Java 8
Kyle Smith
linkedin.com/in/kylesm
@kylesm
• Concurrency improvements
• Default methods
• Functional interfaces
• Lambda expressions
• Method references
• Streams
• Date/time
• Optional
• JavaScript
• JVM PermGen
• Base64 support
• Compact profiles
• Annotation improvements
• Type inference improvements
• Method parameter reflection
• JDBC 4.2
• Concurrency improvements
• Default methods
• Functional interfaces
• Lambda expressions
• Method references
• Streams
• Date/time
• Optional
• JavaScript
• JVM PermGen
• Base64 support
• Compact profiles
• Annotation improvements
• Type inference improvements
• Method parameter reflection
• JDBC 4.2
Themes
• ConcurrentHashMap — all new (inside)!
• LongAdder, DoubleAdder
• StampedLock
• CompletableFuture
Adders
• New classes for concurrent counters
• Waaaayyy more scalable than AtomicLong,etc.
• …if you can tolerate some inaccuracy
LongAdder clicks = new LongAdder();
clicks.increment();
// or counter.add(long)
// ...
clicks.sum();
StampedLock
• Alternative to ReentrantReadWriteLock
• “does not consistently prefer readers over writers or
vice versa"
• Provides optimistic reads
void move(double deltaX, double deltaY){
long stamp = sl.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
sl.unlockWrite(stamp);
}
}
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead();
double currentX = x, currentY = y;
if (!sl.validate(stamp)) {
stamp = sl.readLock();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX
+ currentY * currentY);
}
CompletableFuture
• Everybody wants to be event-driven & reactive
• CompletableFuture allows composition of async
work
CompletableFuture<String> f1 = //…
CompletableFuture<Double> f2 = f1
.thenApply(Integer::parseInt)
.thenApply(r -> r * r * Math.PI);
Default methods
• Interfaces can supply non-abstract methods
• Enables existing interfaces to evolve
• Eliminates the need for companion (“garbage”)
classes
// java.lang.Iterable
default void forEach(Consumer<? super T>
action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
Functional interfaces
• Any interface with a single abstract method
• Examples:
• java.util.Comparator
• java.lang.Runnable
• Can be annotated with @FunctionalInterface
Lambda expressions
• Function values in Java
• Compatible with a functional interface when their
shapes match
• Syntax: (parameters) -> expression
DoubleUnaryOperator op1 =
(double r) -> r * r * Math.PI;
DoubleUnaryOperator op2 =
(r) -> r * r * Math.PI;
Runnable r =
() -> System.out.println("Hi, NEJUG!");
void cut(List<String> l, int len) {
l.replaceAll(s -> s.substring(0, len));
}
Streams
public Collection<Person>
findStudents(List<Person> people) {
Collection<Person> students =
new ArrayList<>();
for (Person p : people) {
if (p.isStudent()) {
students.add(p);
}
}
return students;
}
public Collection<Person>
findStudents(List<Person> people) {
Collection<Person> students =
new ArrayList<Person>();
people.forEach(i -> {
if (i.isStudent()) {
students.add(i);
}
});
return students;
}
public Collection<Person>
findStudents(List<Person> people) {
return people
.stream()
.filter(p -> p.isStudent())
.collect(Collectors.toList());
}
• “ A sequence of elements on which one or more
operations can be performed”
• Operations are either intermediate or terminal
• Streams can be sequential or parallel
• Intermediates:
• map, filter, flatMap, sorted, allMatch, anyMatch,
findAny, findFirst, flatMap, …
• Terminal:
• collect, count, forEach,reduce, max, min, …
long count = values
.stream()
.sorted()
.count();
long count = values
.parallelStream()
.sorted()
.count();
What next?
• Download JDK 8 from java.oracle.com
• IDE Support:
• Eclipse 4.3.2 SR2 (with patches!)
• IntelliJ IDEA 12.0+
• NetBeans IDE 8.0
Can’t move to Java 8?
• Google Guava (Java 6+)
• jsr166e (Java 6+)
• CHMv8, F/J tweaks, StampedLock, etc.
• Mix in some Groovy
• GPars
References:
http://bit.ly/1fRGyQV

What's new in Java 8

  • 1.
    What’s new inJava 8 Kyle Smith linkedin.com/in/kylesm @kylesm
  • 2.
    • Concurrency improvements •Default methods • Functional interfaces • Lambda expressions • Method references • Streams • Date/time • Optional • JavaScript • JVM PermGen • Base64 support • Compact profiles • Annotation improvements • Type inference improvements • Method parameter reflection • JDBC 4.2
  • 3.
    • Concurrency improvements •Default methods • Functional interfaces • Lambda expressions • Method references • Streams • Date/time • Optional • JavaScript • JVM PermGen • Base64 support • Compact profiles • Annotation improvements • Type inference improvements • Method parameter reflection • JDBC 4.2
  • 4.
  • 9.
    • ConcurrentHashMap —all new (inside)! • LongAdder, DoubleAdder • StampedLock • CompletableFuture
  • 10.
  • 11.
    • New classesfor concurrent counters • Waaaayyy more scalable than AtomicLong,etc. • …if you can tolerate some inaccuracy
  • 12.
    LongAdder clicks =new LongAdder(); clicks.increment(); // or counter.add(long) // ... clicks.sum();
  • 14.
  • 15.
    • Alternative toReentrantReadWriteLock • “does not consistently prefer readers over writers or vice versa" • Provides optimistic reads
  • 16.
    void move(double deltaX,double deltaY){ long stamp = sl.writeLock(); try { x += deltaX; y += deltaY; } finally { sl.unlockWrite(stamp); } }
  • 17.
    double distanceFromOrigin() { longstamp = sl.tryOptimisticRead(); double currentX = x, currentY = y; if (!sl.validate(stamp)) { stamp = sl.readLock(); try { currentX = x; currentY = y; } finally { sl.unlockRead(stamp); } } return Math.sqrt(currentX * currentX + currentY * currentY); }
  • 18.
  • 19.
    • Everybody wantsto be event-driven & reactive • CompletableFuture allows composition of async work
  • 20.
    CompletableFuture<String> f1 =//… CompletableFuture<Double> f2 = f1 .thenApply(Integer::parseInt) .thenApply(r -> r * r * Math.PI);
  • 21.
  • 22.
    • Interfaces cansupply non-abstract methods • Enables existing interfaces to evolve • Eliminates the need for companion (“garbage”) classes
  • 23.
    // java.lang.Iterable default voidforEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
  • 24.
  • 25.
    • Any interfacewith a single abstract method • Examples: • java.util.Comparator • java.lang.Runnable • Can be annotated with @FunctionalInterface
  • 26.
  • 27.
    • Function valuesin Java • Compatible with a functional interface when their shapes match • Syntax: (parameters) -> expression
  • 28.
    DoubleUnaryOperator op1 = (doubler) -> r * r * Math.PI; DoubleUnaryOperator op2 = (r) -> r * r * Math.PI; Runnable r = () -> System.out.println("Hi, NEJUG!"); void cut(List<String> l, int len) { l.replaceAll(s -> s.substring(0, len)); }
  • 29.
  • 30.
    public Collection<Person> findStudents(List<Person> people){ Collection<Person> students = new ArrayList<>(); for (Person p : people) { if (p.isStudent()) { students.add(p); } } return students; }
  • 31.
    public Collection<Person> findStudents(List<Person> people){ Collection<Person> students = new ArrayList<Person>(); people.forEach(i -> { if (i.isStudent()) { students.add(i); } }); return students; }
  • 32.
    public Collection<Person> findStudents(List<Person> people){ return people .stream() .filter(p -> p.isStudent()) .collect(Collectors.toList()); }
  • 33.
    • “ Asequence of elements on which one or more operations can be performed” • Operations are either intermediate or terminal • Streams can be sequential or parallel
  • 34.
    • Intermediates: • map,filter, flatMap, sorted, allMatch, anyMatch, findAny, findFirst, flatMap, … • Terminal: • collect, count, forEach,reduce, max, min, …
  • 35.
    long count =values .stream() .sorted() .count(); long count = values .parallelStream() .sorted() .count();
  • 36.
    What next? • DownloadJDK 8 from java.oracle.com • IDE Support: • Eclipse 4.3.2 SR2 (with patches!) • IntelliJ IDEA 12.0+ • NetBeans IDE 8.0
  • 37.
    Can’t move toJava 8? • Google Guava (Java 6+) • jsr166e (Java 6+) • CHMv8, F/J tweaks, StampedLock, etc. • Mix in some Groovy • GPars
  • 38.

Editor's Notes

  • #5 Release themes
  • #6 Developer productivity Tools to generate code, languages to reduce ceremony, frameworks to remove boilerplate Images taken from their respective project sites.
  • #7 Improve application performance Then: 1-2 CPUs, synchronized keyword and direct use of threads Image source: http://en.wikipedia.org/wiki/File:Inside_and_Rear_of_Webserver.jpg
  • #8 Now: Dell PowerEdge M915: 64 cores per blade Today’s world: lock-free, non-blocking, little to no synchronization, immutability use of thread pools or higher-level abstractions Image source: http://en.community.dell.com/dell-blogs/direct2dell/b/direct2dell/archive/2011/11/29/a-little-clarity.aspx
  • #9 Alternate now: the cloud. Oh yeah, and distributed. Image source: http://www.google.com/about/datacenters/gallery/#/tech/20
  • #11 CHM pre-v8: 1.6 kb memory (empty) vs 100 bytes (Hashtable) v8 much closer now
  • #12 Adders
  • #13 AtomicLong - CAS, spin lock under high contention
  • #14 LA works by trying to have threads operate on different variables. Internally it’s a hash table of cells (akin to AtomicLongs) and hashing thread IDs means most threads will write to uncontended cells Number of cells grows as the contention grows
  • #15 Works significantly better under contention than AtomicLong Image source: http://blog.palominolabs.com/2014/02/10/java-8-performance-improvements-longadder-vs-atomiclong/
  • #16 StampedLock
  • #17 Java 5: ReentrantRWL favors readers Java 6: RRWL favors writers
  • #18 Example from the StampedLock Javadoc StampedLock is not re-entrant, but performs better than RRWL
  • #19 Example from the StampedLock Javadoc
  • #20 The stamp from tryOptimisticRead is only good for validation, not unlocking as read/write lock stamps are
  • #21 CompletableFuture
  • #22 Very useful for building event-driven/reactive systems, execution pipelines Overly complex to manage the flow w/callbacks Hard to write code that is easy to reason about CF makes it easy to build a workflow Kind of like promises in JavaScript
  • #23 Switch to Javadoc if time Example from http://www.nurkiewicz.com/2013/05/java-8-definitive-guide-to.html
  • #24 Method references
  • #25 Static, non-static, even constructors
  • #26 Example from http://winterbe.com/posts/2014/03/16/java-8-tutorial/
  • #27 Default methods
  • #28 Uses ‘default’ keyword Classes win over interfaces; if a class in the superclass chain supplies a declaration (concrete or abstract) the class wins every time; defaults won’t matter ⁃ More specific interfaces win (where “specificity” == sub-typing); default from List beats default from Collection ⁃ If there’s not a unique winner from #1 & #2 concrete class must disambiguate manually Object methods about state, interfaces don’t have state, classes do
  • #30 Functional interfaces
  • #31 Show Javadoc for java.util.function
  • #32 Lambda expressions
  • #33 Anonymous functions Act as closure (“capturing” or not) “Capturing” if it accesses non-static variables from outside lambda body Doesn’t define a new scope like inner classes Compatible with a FI when their shapes match Better libraries in Java
  • #36 Streams
  • #37 Java 1.4
  • #38 Java 5 w/new for loop
  • #39 Java 7
  • #40 Java 8
  • #42 Allows you get away from imperative programming and let the libraries decide Separates ‘what you want to do’ from ‘how you want to do it’
  • #43 Show Javadoc page for Stream
  • #44 Example from B. Winterberg: http://winterbe.com/posts/2014/03/16/java-8-tutorial/
  • #45 sequential sort took: 794 ms
  • #46 parallel sort took: 277 ms
  • #47 sequential sort took: 794 ms