Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java SE 8 for Java EE Developers

144 views

Published on

Java SE 8 brings a bounty of improvements - Lambda expressions, the new Date Time API, Completable Futures, streams and repeatable annotations. In this session we will explore how these features can be utilized inside Java EE 8 applications with APIs such as Servlet, JAX-RS, JSON-P, JSF, EJB 3, JPA and Java EE Concurrency Utilities.

Published in: Technology
  • Login to see the comments

  • Be the first to like this

Java SE 8 for Java EE Developers

  1. 1. Java SE 8 for Java EE Developers Reza Rahman Senior Vice President, Author, Blogger reza_rahman@lycos.com @reza_rahman
  2. 2. Java SE 8 and Java EE • Java SE 8 is one of the most significant releases in years • Extremely well adopted • Java EE 7 runtimes already support Java SE 8 • Specific Java SE 8 alignment done in Java EE 8
  3. 3. Lambdas • Introducing functional programming without breaking Java • Requires change in thinking to become true believer • Practical benefits for the rest of us • Streams, CompletableFuture • An actual syntax change at the language level • Syntactic sugar over anonymous inner classes?
  4. 4. Lambdas The Problem List<Student> students = ... double highestScore = 0.0; for (Student s : students) { if (s.gradYear == 2011) { if (s.score > highestScore) { highestScore = s.score; } }
  5. 5. Lambdas 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();
  6. 6. Lambdas The Elegant Solution SomeList<Student> students = ... double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max();
  7. 7. Asynchronous Servlet and Lambdas @WebServlet(urlPatterns={"/report"}, asyncSupported=true) public class AsyncServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { ... final AsyncContext asyncContext = request.startAsync(); asyncContext.start(() -> { ReportParameters parameters = parseReportParameters(asyncContext.getRequest()); Report report = generateReport(parameters); printReport(report, asyncContext); asyncContext.complete(); }); } }
  8. 8. Streams • Applying lambdas to the Collections API • Bulk operations • Sequence (“stream”) of data int sum = transactions.stream(). filter(t -> t.getBuyer().getCity().equals(“Philly”)). mapToInt(Transaction::getPrice). sum(); Source Intermediate operation Terminal operation
  9. 9. JSON-P Stream [ { "name":"Duke", "gender":"male", "phones":[ "home":"650‐123‐4567", "mobile":"650‐111‐2222" ] }, { "name":"Jane", ... ] JsonArray contacts = Json.createArrayBuilder() .add(...
  10. 10. JSON-P Stream JsonArray females = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "female".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect(JsonCollectors.toJsonArray());
  11. 11. Date/TimeAPI • Significant improvement over current Java date types • Date, Calendar • Unified, comprehensive, modern model • Builder pattern, fluent API • Manipulating temporal values • Better internationalization
  12. 12. Date/TimeAPI Key Artifacts • LocalTime • LocalDate • LocalDateTime • ZonedDateTime • Instant • Duration • Period
  13. 13. Date/TimeAPI Examples // Get the current date and time LocalDateTime now = LocalDateTime.now(); // Returns formatted date and time // “2013-10-21T20:25:15:16.256” now.toString(); // Add 5 hours LocalDateTime later = now.plus(5, HOURS); // Subtract 2 days LocalDateTime earlier = now.minus(2, DAYS);
  14. 14. Date/TimeAPI with JPA @Entity public class Accident { @Temporal(TemporalType.TIMESTAMP) @Past private Instant when; }
  15. 15. Date/TimeAPI with JSF <h:form> <h:inputText id = “date” value = “#{registerAccident.when}” size = “20” required=“true” label = “when” /> ... @Named @ViewScoped public class RegisterAccident { Instant when; ...
  16. 16. Repeatable Annotations • In Java SE 8, annotations can now be repeated • A lot of applicabilityin Java EE • @DataSourceDefinition • @NamedQuery • @JMSDestinationDefinition • @JMSConnectionFactoryDefinition • @MailSessionDefinition • @Schedule
  17. 17. Repeatable Annotations in Java EE @NamedQueries({ @NamedQuery(name=SELECT_ALL, query="..."), @NamedQuery(name=COUNT_ALL, query="...") }) public class Customer { ... @NamedQuery(name=SELECT_ALL, query="...") @NamedQuery(name=COUNT_ALL, query="...") public class Customer { ...
  18. 18. Completable Future • Futures and callbacks both have serious flaws • Especiallywhen it comes to significantly“reactive” code • CompletableFuture significantly better • Non-blocking, event-driven, composable and functional (via lambdas) • JavaScript “promises” for Java
  19. 19. Looks are Deceiving… Person p = ... Assets assets = getAssets(p); Liabilities liabilities = getLiabilities(p); Credit credit = calculateCreditScore(assets, liabilities); History history = getHealthHistory(p); Health health = calculateHeathScore(history); Coverage coverage = underwrite(credit, health);
  20. 20. The Problem with Futures (and Callbacks) Person p = ... Future<Assets> f1 = executor.submit(() -> getAssets(p)); Future<Liabilities> f2 = executor.submit( () -> getLiabilities(p)); Future<Credit> f3 = executor.submit( () -> calculateCreditScore(f1.get(), f2.get())); // The unrelated calls below are now blocked for no reason Future<History> f4 = executor.submit(() -> getHealthHistory(p)); Future<Health> f5 = executor.submit( () -> calculateHeathScore(f4.get())); // Unrelated paths join below Future<Coverage> f6 = executor.submit( () -> underwrite(f3.get(), f5.get())); Callbacks don’t block, but introduce callback hell… https://github.com/m-reza-rahman/reactive_javaee/blob/master/CallbackHell.java
  21. 21. CompletableFuture Basics public CompletableFuture<Confirmation> processPayment( Order order) { CompletableFuture<Confirmation> future = new CompletableFuture<>(); executor.execute(() -> { Confirmation status = ... future.complete(status); }); return future; } paymentService .processPayment(order) .thenAccept( confirmation -> System.out.println(confirmation));
  22. 22. 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();
  23. 23. CompletableFuture with JAX-RS CompletionStage<Assets> getAssets = client .target("assets/{ssn}") .resolveTemplate("ssn", person.getSsn()) .request("application/json") .rx() .get(Assets.class); CompletionStage<Liabilities> getLiabilities = client .target("liabilities/{ssn}") .resolveTemplate("ssn", person.getSsn()) .request("application/json") .rx() .get(Liabilities.class); Coverage coverage = getAssets.thenCombine(getLiabitities, (assets, liabilities) -> underwrite(assets, liabilities)) .toCompletableFuture().join();
  24. 24. Java EE 8/GlassFish 5 Release https://blogs.oracle.com/theaquarium/java-ee-8-is-final-and-glassfish-50-is-released
  25. 25. Jakarta EE https://jakarta.ee
  26. 26. Summary • Java SE 8 is one of the most significant releases in years • Most Java EE 7 runtimes support Java SE 8 • Java EE 8 has been aligned with Java SE 8

×