JavaSE.Next – Java SE 8, Java SE 9 and Beyond

25
Others Talk, We Listen. JavaSE.Next – Java SE 8, Java SE 9 and Beyond Reza Rahman Senior Architect [email protected] @reza_rahman

Transcript of JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Page 1: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Others Talk, We Listen.

JavaSE.Next – Java SE 8, Java SE 9 and BeyondReza RahmanSenior [email protected]@reza_rahman

Page 2: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

CapTech

Full-service US national IT consulting firm that focuses on client best interests, trust, servant leadership, culture, professionalism and technical excellence.

#28 in Vault's Consulting Top 50#3 Best Consulting Internship#9 Best Overall Internship

#1 in Meeting Client’s Needs#7 Best Firm to Work For#1 in Career Development

Ranked for the 7th Consecutive Year

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 3: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Java SE 8

• The most significant release for Java SE for a while• Lambdas, streams• Date/time API• CompletableFuture• Much, much more

• Very strong adoption so far

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 4: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Lambdas

• Introducing functional programming without breaking Java• Imperative to Declarative• Requires change in thinking to become true believer• Practical benefits for the rest of us• Streams, CompletableFuture• Forward compatible

• An actual syntax change at the language level• Syntactic sugar over anonymous inner classes?• Anonymous function• Parameterized business logic as data

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 5: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Lambdas

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

The Problem

List<Student> students = ...double highestScore = 0.0;for (Student s : students) { if (s.gradYear == 2011) { if (s.score > highestScore) { highestScore = s.score; } }

Page 6: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Lambdas

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

An Inelegant Solution

List<Student> students = ...double highestScore = students. filter(new Predicate<Student>() { public boolean op(Student s) { return s.getGradYear() == 2011; } }). map(new Mapper<Student,Double>() { public Double extract(Student s) { return s.getScore(); } }). max();

Page 7: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Lambdas

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

The Elegant Solution

SomeList<Student> students = ...double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max();

Page 8: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Functional Interfaces

• The type of a lambda is a functional interface• Historically single-method interfaces have represented functions

• Runnable, Comparator, ActionListener• With lambdas they now have a name - functional interfaces

• Add some useful new ones like Predicate<T>, Consumer<T>, Supplier<T>

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Predicate<String> isEmpty = s -> s.isEmpty();

Page 9: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

java.util.function Package

• Predicate<T>• Determine if the input of type T matches some criteria

• Consumer<T>• Accept a single input argument of type T, and return no result

• Function<T,R>• Apply a function to the input type T, generating a result of type R

• Supplier<T>, UnaryOperator<T>, BinaryOperator<T>, IntConsumer, ToIntFunction<T>, BiFunction<T,U,R>

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 10: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Streams

• Applying lambdas to the Collections API• Bulk operations• Sequence (“stream”) of data• Filter, map, reduce

• Performance, performance, performance• Lazy processing• Parallel processing

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 11: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Streams

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Pipeline

• A stream pipeline consists of three parts• A source• Zero or more intermediate operations• A terminal operation

int sum = transactions.stream(). filter(t -> t.getBuyer().getCity().equals(“Philly”)). mapToInt(Transaction::getPrice). sum();

Source

Intermediate operation

Terminal operation

Page 12: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Date/Time API

• Significant improvement over current Java date types• Date, Calendar, DateFormat

• Unified, comprehensive, modern model• Builder pattern, fluent API• Manipulating temporal values• Better internationalization• Battle tested

• No need for Joda-Time any more• Interoperate with existing classes

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 13: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Date/Time API

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Key Artifacts

• LocalTime• LocalDate• LocalDateTime• ZonedDateTime• Clock• Instant

• Duration• Period• ZoneId• Month• Year• DayOfWeek

Page 14: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Date/Time API Examples

// Get the current date and timeLocalDateTime now = LocalDateTime.now();

// Returns formatted date and time // “2013-10-21T20:25:15:16.256”now.toString();

// Add 5 hoursLocalDateTime later = now.plus(5, HOURS);

// Subtract 2 daysLocalDateTime earlier = now.minus(2, DAYS);

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 15: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

More Date/Time API Examples

LocalDate today = LocalDate.now();LocalDate bday = LocalDate.of(1979, 3, 10);Period timeAlive = Period.between(bday, today);int age = timeAlive.getYears();

// Periods can also be used as arguments in the .plus() // and .minus() methodsLocalDate calculatedBday = today.minus(timeAlive);

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 16: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Completable Future

• Futures and callbacks both have serious flaws• Especially when it comes to significantly “reactive” code

• CompletableFuture significantly better• Non-blocking, event-driven, composable and functional (via lambdas)

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 17: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Looks are Deceiving…

Person p = ...Assets assets = getAssets(p);Liabilities liabilities = getLiabilities(p);Credit credit = calculateCreditScore(assets, liabilities);

History history = getHealthHistory(p);Health health = calculateHealthScore(history);

Coverage coverage = underwrite(credit, health);

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 18: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

The Problem with Futures (and Callbacks)

Person p = ...Future<Assets> f1 = getAssets(p);Future<Liabilities> f2 = getLiabilities(p);Future<Credit> f3 = calculateCreditScore(f1.get(), f2.get());

// The unrelated calls below are now blocked for no reasonFuture<History> f4 = getHealthHistory(p);Future<Health> f5 = calculateHealthScore(f4.get());

// Unrelated paths join belowFuture<Coverage> f6 = underwrite(f3.get(), f5.get());

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Callbacks don’t block, but introduce callback hell…https://github.com/m-reza-rahman/reactive_javaee/blob/master/CallbackHell.java

Page 19: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

CompletableFuture Basics

public CompletableFuture<Confirmation> processPayment( Order order) { CompletableFuture<Confirmation> future = new CompletableFuture<>(); executor.execute(() -> { Confirmation status = ... future.complete(status); }); return future;}

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

paymentService .processPayment(order) .thenAccept( confirmation -> System.out.println(confirmation));

Page 20: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Functional Reactive to the Rescue?

CompletableFuture<Assets> getAssets = CompletableFuture.supplyAsync(() -> getAssets(person));CompletableFuture<Liabilities> getLiabilities = CompletableFuture.supplyAsync(() -> getLiabilities(person));CompletableFuture<Credit> calculateCreditScore = getAssets.thenCombineAsync(getLiabilities, (assets, liabilities) -> calculateCreditScore(assets, liabilities));

CompletableFuture<Health> calculateHeathScore = CompletableFuture.supplyAsync(() -> getHealthHistory(person)) .thenApplyAsync(history -> calculateHeathScore(history));

Coverage coverage = calculateCreditScore.thenCombineAsync(calculateHeathScore, (credit, health) -> underwrite(credit, health)).join();

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 21: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Others

• Remove PermGen, rarely used GC combinations• Optional<T>• Default methods• Repeatable annotations• Fork/join common pool• Parallel array sorting• Standard Encoding and Decoding Base64• JDBC 4.2• Compact profiles• Many more

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 22: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Java SE 9

• Jigsaw/modularity• HTTP/2 (and WebSocket) client• Make G1 default GC• Java Shell/REPL (Read-Eval-Print Loop)• Reactive streams• Deprecating Applets• Other minor features

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 23: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Summary

• Java SE 8 most significant release in years.• Well-received and adopted.• More important changes coming in Java SE 9.• Now is the time to get involved and provide feedback.

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 24: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Resources

• Java SE Tutorials• http://docs.oracle.com/javase/tutorial/

• What's New in JDK 8• http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.ht

ml• JDK 8 Features

• http://openjdk.java.net/projects/jdk8/features• JDK 9

• http://openjdk.java.net/projects/jdk9/

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.

Page 25: JavaSE.Next – Java SE 8, Java SE 9 and Beyond

Copyright © 2015 CapTech Ventures, Inc. All rights reserved.