JavaSE.Next – Java SE 8, Java SE 9 and Beyond
-
Upload
reza-rahman -
Category
Technology
-
view
8.995 -
download
2
Transcript of 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
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.
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.
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.
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; } }
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();
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();
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();
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.
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.
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
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.
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
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.
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.
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.
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.
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
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));
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.
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.
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.
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.
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.
Copyright © 2015 CapTech Ventures, Inc. All rights reserved.