SlideShare a Scribd company logo
Java SE 8 for Java
EE Developers
Reza Rahman
Senior Vice President, Author, Blogger
reza_rahman@lycos.com
@reza_rahman
https://axoniq.io
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
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?
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;
}
}
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();
Lambdas
The Elegant Solution
SomeList<Student> students = ...
double highestScore = students.
filter(Student s -> s.getGradYear() == 2011).
map(Student s -> s.getScore()).
max();
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();
});
}
}
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
JSON-P Stream
[
{
"name":"Duke",
"gender":"male",
"phones":[
"home":"650‐123‐4567",
"mobile":"650‐111‐2222"
]
},
{
"name":"Jane", ...
]
JsonArray contacts =
Json.createArrayBuilder()
.add(...
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());
Date/Time API
• Significant improvement over current Java date types
• Date, Calendar
• Unified, comprehensive, modern model
• Builder pattern, fluent API
• Manipulating temporal values
• Better internationalization
Date/Time API
Key Artifacts
• LocalTime
• LocalDate
• LocalDateTime
• ZonedDateTime
• Instant
• Duration
• Period
Date/Time API 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);
Date/Time API with JPA
@Entity
public class Accident {
@Temporal(TemporalType.TIMESTAMP)
@Past
private Instant when;
}
Date/Time API with JSF
<h:form>
<h:inputText id = “date”
value = “#{registerAccident.when}”
size = “20” required=“true”
label = “when” />
...
@Named @ViewScoped
public class RegisterAccident {
Instant when;
...
Repeatable Annotations
• In Java SE 8, annotations can now be repeated
• A lot of applicability in Java EE
• @DataSourceDefinition
• @NamedQuery
• @JMSDestinationDefinition
• @JMSConnectionFactoryDefinition
• @MailSessionDefinition
• @Schedule
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 {
...
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)
• JavaScript “promises” for Java
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);
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
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));
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();
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();
Java EE 8/GlassFish 5 Release
https://blogs.oracle.com/theaquarium/java-ee-8-is-final-and-glassfish-50-is-released
Jakarta EE
https://jakarta.ee
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
TDC2018SP | Trilha Java - Java SE 8 for Java EE Developers

More Related Content

PDF
Templating you're doing it wrong - Nikolas Martens - Codemotion Amsterdam 2017
PDF
Templates don’t need to break the browser by Nikolas Martens
PDF
Finch.io - Purely Functional REST API with Finagle
PDF
The Django Web Framework (EuroPython 2006)
PPTX
Extending Slate Queries & Reports with JSON & JQUERY
PDF
JavaCro 2014 Scala and Java EE 7 Development Experiences
PDF
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
PDF
Http4s, Doobie and Circe: The Functional Web Stack
Templating you're doing it wrong - Nikolas Martens - Codemotion Amsterdam 2017
Templates don’t need to break the browser by Nikolas Martens
Finch.io - Purely Functional REST API with Finagle
The Django Web Framework (EuroPython 2006)
Extending Slate Queries & Reports with JSON & JQUERY
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
Http4s, Doobie and Circe: The Functional Web Stack

Similar to TDC2018SP | Trilha Java - Java SE 8 for Java EE Developers (20)

PPTX
Bare-knuckle web development
PDF
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
PDF
Phoenix + Reactで 社内システムを 密かに作ってる
PPSX
What's New In C# 7
PDF
The journey of an (un)orthodox optimization
PDF
Understanding backbonejs
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
KEY
Let's build a parser!
ODP
Pick up the low-hanging concurrency fruit
PDF
Webmontag Berlin "coffee script"
KEY
Jython: Python para la plataforma Java (EL2009)
KEY
Jython: Python para la plataforma Java (JRSL 09)
PDF
Functional Principles for OO Developers
PDF
Casting for not so strange actors
KEY
Async. and Realtime Geo Applications with Node.js
PPTX
Understanding Async/Await in Javascript
ODP
Concurrency on the JVM
PDF
Redux vs Alt
PPTX
Tools for Making Machine Learning more Reactive
PDF
async/await Revisited
Bare-knuckle web development
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Phoenix + Reactで 社内システムを 密かに作ってる
What's New In C# 7
The journey of an (un)orthodox optimization
Understanding backbonejs
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Let's build a parser!
Pick up the low-hanging concurrency fruit
Webmontag Berlin "coffee script"
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (JRSL 09)
Functional Principles for OO Developers
Casting for not so strange actors
Async. and Realtime Geo Applications with Node.js
Understanding Async/Await in Javascript
Concurrency on the JVM
Redux vs Alt
Tools for Making Machine Learning more Reactive
async/await Revisited
Ad

More from tdc-globalcode (20)

PDF
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
PDF
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
PDF
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
PDF
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
PDF
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
PDF
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
PDF
TDC2019 Intel Software Day - Inferencia de IA em edge devices
PDF
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
PPT
Trilha .Net - Programacao funcional usando f#
PDF
TDC2018SP | Trilha Go - Case Easylocus
PDF
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
PDF
TDC2018SP | Trilha Go - Clean architecture em Golang
PDF
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
PDF
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
PDF
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
PDF
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
PDF
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
PDF
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
PDF
TDC2018SP | Trilha .Net - .NET funcional com F#
PDF
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
TDC2019 Intel Software Day - Visao Computacional e IA a servico da humanidade
TDC2019 Intel Software Day - Tecnicas de Programacao Paralela em Machine Lear...
TDC2019 Intel Software Day - ACATE - Cases de Sucesso
TDC2019 Intel Software Day - Otimizacao grafica com o Intel GPA
TDC2019 Intel Software Day - Deteccao de objetos em tempo real com OpenVino
TDC2019 Intel Software Day - OpenCV: Inteligencia artificial e Visao Computac...
TDC2019 Intel Software Day - Inferencia de IA em edge devices
Trilha BigData - Banco de Dados Orientado a Grafos na Seguranca Publica
Trilha .Net - Programacao funcional usando f#
TDC2018SP | Trilha Go - Case Easylocus
TDC2018SP | Trilha Modern Web - Para onde caminha a Web?
TDC2018SP | Trilha Go - Clean architecture em Golang
TDC2018SP | Trilha Go - "Go" tambem e linguagem de QA
TDC2018SP | Trilha Mobile - Digital Wallets - Seguranca, inovacao e tendencia
TDC2018SP | Trilha .Net - Real Time apps com Azure SignalR Service
TDC2018SP | Trilha .Net - Passado, Presente e Futuro do .NET
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Obtendo metricas com TDD utilizando build automatiz...
TDC2018SP | Trilha .Net - .NET funcional com F#
TDC2018SP | Trilha .Net - Crie SPAs com Razor e C# usando Blazor em .Net Core
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
01-Introduction-to-Information-Management.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
Trump Administration's workforce development strategy
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
RMMM.pdf make it easy to upload and study
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Microbial disease of the cardiovascular and lymphatic systems
LDMMIA Reiki Yoga Finals Review Spring Summer
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Computing-Curriculum for Schools in Ghana
01-Introduction-to-Information-Management.pdf
Weekly quiz Compilation Jan -July 25.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Trump Administration's workforce development strategy
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH

TDC2018SP | Trilha Java - Java SE 8 for Java EE Developers

  • 1. Java SE 8 for Java EE Developers Reza Rahman Senior Vice President, Author, Blogger reza_rahman@lycos.com @reza_rahman
  • 3. 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
  • 4. 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?
  • 5. 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; } }
  • 6. 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();
  • 7. Lambdas The Elegant Solution SomeList<Student> students = ... double highestScore = students. filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max();
  • 8. 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(); }); } }
  • 9. 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
  • 11. 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());
  • 12. Date/Time API • Significant improvement over current Java date types • Date, Calendar • Unified, comprehensive, modern model • Builder pattern, fluent API • Manipulating temporal values • Better internationalization
  • 13. Date/Time API Key Artifacts • LocalTime • LocalDate • LocalDateTime • ZonedDateTime • Instant • Duration • Period
  • 14. Date/Time API 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);
  • 15. Date/Time API with JPA @Entity public class Accident { @Temporal(TemporalType.TIMESTAMP) @Past private Instant when; }
  • 16. Date/Time API with JSF <h:form> <h:inputText id = “date” value = “#{registerAccident.when}” size = “20” required=“true” label = “when” /> ... @Named @ViewScoped public class RegisterAccident { Instant when; ...
  • 17. Repeatable Annotations • In Java SE 8, annotations can now be repeated • A lot of applicability in Java EE • @DataSourceDefinition • @NamedQuery • @JMSDestinationDefinition • @JMSConnectionFactoryDefinition • @MailSessionDefinition • @Schedule
  • 18. 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 { ...
  • 19. 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) • JavaScript “promises” for Java
  • 20. 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);
  • 21. 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
  • 22. 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));
  • 23. 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();
  • 24. 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();
  • 25. Java EE 8/GlassFish 5 Release https://blogs.oracle.com/theaquarium/java-ee-8-is-final-and-glassfish-50-is-released
  • 27. 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