Java SE 8 and Java EE 7 Overview
Peter Doschkinow
Senior Java Architect
The following is intended to outline our general product direction. It is intended
for information purposes only, and may not be incorporated into any contract.
It is not a commitment to deliver any material, code, or functionality, and should
not be relied upon in making purchasing decisions. The development, release,
and timing of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Agenda
Java SE 8 New Features
– Language
– Libraries
– Platform and JVM
Java EE 7 Overview
– Focus on HTML5 support
New functionality
– JSR 308: Annotations on types
– JSR 310: Date and Time API
– JSR 335: Lambda expressions
Updated functionality
– JSR 114: JDBC Rowsets
– JSR 160: JMX Remote API
– JSR 199: Java Compiler API
– JSR 173: Streaming API for XML
– JSR 206: Java API for XML Processing
– JSR 221: JDBC 4.0
– JSR 269: Pluggable Annotation-Processing API
Component JSRs
Java SE 8 (JSR 337)
Biggest changes to the Java language since Java SE 5
Significant enhancements in the class libraries
The main goals of these changes are:
– Better developer productivity
– More reliable code
– Better utilisation of multi-core and multi-processor systems
Code is no longer inherently serial or parallel
Java SE 8
Lambda expressions provide anonymous function types to Java
– Replace use of anonymous inner classes
– Provide more functional style of programming in Java
Closures and Functional Programming
Lambda Expressions
doSomething(new DoStuff() {
public boolean isGood(int value) {
return value == 42;
}
});
doSomething(answer -> answer == 42);
Simplified to:
class Person {
String name;
int age;
String getName() { return name; }
int getAge() { return age; }
}
List<Person> list = ... ;
Collections.sort(list, ???);
Sorting a list of objects
Lambda Expressions Example
List<Person> list = ... ;
class ComparePersonsByName implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
Collections.sort(list, new ComparePersonsByName());
Sorting a list of objects traditionally
Lambda Expressions Example
List<Person> list = ... ;
Collections.sort(list,
(p1, p2) -> p1.getName().compareTo(p2.getName())
Collections.sort(list, Comparator.comparing(p -> p.getName())
Sorting a list of objects with lambdas
Lambda Expressions Example
List<Person> list = ... ;
Collections.sort(list,
(p1, p2) -> p1.getName().compareTo(p2.getName())
Collections.sort(list, Comparator.comparing(p -> p.getName())
Collections.sort(list, Comparator.comparing(Person::getName)
Sorting a list of objects with lambdas and method references
Lambda Expressions Example
Provide a mechanism to add new methods to existing interfaces
– Without breaking backwards compatability
– Gives Java multiple inheritance of behaviour, as well as types (but not
state!)
Bringing Multiple Inheritance (of Functionality) to Java
Extension Methods
public interface Set<T> extends Collection<T> {
public int size();
... // The rest of the existing Set methods
public T reduce(Reducer<T> r)
default Collections.<T>setReducer;
}
Annotations can currently only be used on type declarations
– Classes, methods, variable definitions
Extension for places where types are used
– e.g. parameters
Permits error detection by pluggable type checkers
– e.g. null pointer errors, race conditions, etc
Annotations On Java Types
public void process(@notnull List data) {…}
Mechanism to retrieve parameter names of methods and constructors
– At runtime via core reflection
Improved code readability
– Eliminate redundant annotations
Improve IDE capabilities
– Auto-generate template code
Method and Constructor now inherit from new Executable class
– getParameters() returns array of Parameter objects
– Name, type, annotations for each parameter
Access To Parameter Names At Runtime
Repeating annotations
Multiple annotations with the same type applied to a single program element
No more apt tool and associated API
– Complete the transition to the JSR 269 implementation
DocTree API
– Provide access to the syntactic elements of a javadoc comment
DocLint tool
– Use DocTree API to identify basic errors in javadoc comments
Small Things @OneToOne @JoinColumn(name=“PARTNUM”) @JoinColumn(name=“PARTREV”) public Part getPart() { return part; }
No small task!
– Java SE 7 has 4024 standard classes
Modernize general library APIs
Improve performance
– Gains from use of invokedynamic to implement Lambdas
Demonstrate best practices for extension methods
Enhance Core Libraries With Lambdas
java.util.function package
– Function, Predicate, Consumer, Supplier interfaces
java.util.stream package
– Stream, Collector interfaces
Hidden implicit iteration
Serial and parallel implementations
– Generally expressed with Lambda statements
Parallel implementation builds on Fork-Join framework
Lazy evaluation
Filter, Map, Reduce for Java
Bulk Data Operations For Collections
List<Person> persons = ...
int oldestPeter = persons.stream()
.filter(p -> p.getName() == “Peter”)
.map(p -> p.getAge())
.max();
Java Streams API
Source
Stream Intermediate
Stream Result Intermediate
Stream
filter map max
Higher abstraction view on
Collections
Uses the Unix concept of
fipes and filters
No storage
Functional in nature
Seeks laziness
List<Person> persons = ...
int oldestPeter = persons.parallelStream()
.filter(p -> p.getName() == “Peter”)
.map(p -> p.getAge())
.max();
Java Streams API
Source
Stream Intermediate
Stream Result Intermediate
Stream
filter map max
Higher abstraction view on
Collections
Uses the Unix concept of
fipes and filters
No storage
Functional in nature
Seeks laziness
Support parallel execution
using Fork-and-Join
framework
A new date, time, and calendar API for the Java SE platform
Supports standard time concepts
– Partial, duration, period, intervals
– date, time, instant, and time-zone
Provides a limited set of calendar systems and be extensible to others
Uses relevant standards, including ISO-8601, CLDR, and BCP47
Based on an explicit time-scale with a connection to UTC
Date And Time APIs
Currently developers are forced to use non-public APIs
– sun.misc.BASE64Encoder
– sun.misc.BASE64Decoder
Java SE 8 now has a standard way
– java.util.Base64.Encoder
– java.util.Base64.Decoder
– encode, encodeToString, decode, wrap methods
Base64 Encoding and Decoding
New Modern Theme: Modena
JavaFX 3D
Rich Text
New widgets: TreeTableView, DatePicker
Public API for CSS structure
WebView Enhancements
Embedded Support
Support the direct launching of JavaFX applications
– Enhancement to the java command line launcher
JavaFX 8 New Features
Optimize java.text.DecimalFormat.format
– Improve performance of common DecimalFormat usages
Statically Linked JNI Libraries
– Needed for embedded applications
– Currently only dynamically linked supported
Handle frequent HashMap collisions with balanced trees
– Hash bucket switches from linked list to balanced tree at certain threshold
to improve performance
Small Things
Approximate static footprint goals
Compact Profiles
Compact1 Profile
Compact2 Profile
Compact3 Profile
Full JRE 140Mb
24Mb
17Mb
10Mb
Fix some assumptions about classloaders
Use ServiceLoader rather than proprietary SPI code
– E.g. JAXP does not use ServiceLoader
JDK tool to analyse application code dependencies: jdeps
Deprecate APIs that will impede modularisation
– e.g. java.util.logging.LogManager.addPropertyChangeListener
Getting Ready For Jigsaw
Modularisation Preparation
Improve performance, quality, and portability of method handles and
invokedynamic
Reduce the amount of assembly code in the JVM
Reduce native calls during method handle processing
Better reference implementation of JSR 292 (invokedynamic)
Assembly language code re-written in Java
Lambda-Form Representation For Method Handles
Lightweight, high-performance JavaScript engine
– Integrated into JRE
Use existing javax.script API
ECMAScript-262 Edition 5.1 language specification compliance
New command-line tool, jjs to run JavaScript
Internationalised error messages and documentation
Nashorn JavaScript Engine
Rarely used
– DefNew + CMS
– ParNew + SerialOld
– Incremental CMS
Large testing effort for little return
Will generate deprecated option messages
– Won’t disappear just yet
Retire Rarely-Used GC Combinations
Part of the HotSpot, JRockit convergence
Current objects moved to Java heap or native memory
– Interned strings, class metadata, class static variables
Metaspace – for native allocation
– Limited only by process address space
– To force a limit use -XX:MaxMetaspaceSize=<size>
Class Data Sharing – Experimental feature
– Available on all platforms, -Xshare:<flag>
– Reduce footprint and startup by sharing JDK classes between processes
Permanently
Remove The Permanent Generation
Autoconf based build system
– ./configure style build setup
Enhance javac to improve build speed
– Run on all available cores
– Track package and class dependences between builds
– Automatically generate header files for native methods
– Clean up class and header files that are no longer needed
Increased Build Speed, Simplified Setup
The JDK
The Java EE Journey
Java EE 7
2005-2012
Ease of
Development
Lightweight
Developer Productivity & HTML5
1998-2004
Enterprise
Java Platform
Robustness
Web
Services
2013 - Future
Java EE 7 Themes
Batch
Concurrency
Simplified JMS
More annotated POJOs
Less boilerplate code
Cohesive integrated
platform
DEVELOPER
PRODUCTIVITY
JAX-RS
WebSockets
JSON
Servlet NIO
MEETING
ENTERPRISE
DEMANDS
Java EE 7
Java EE 7 JSRs
TCP based, bi-directional, full-duplex
messaging
Originally proposed as part of HTML5
IETF-defined Protocol: RFC 6455
– Handshake, data transfer
W3C defined JavaScript API
– Candidate Recommendation
Supported by most browser already http://caniuse.com/websockets
WebSocket
Starts with HTTP handshake
– Supports HTTP proxies, filtering, authentication and intermediaries
Data transfer
– Text/Binary frames
– Ping/Pong control frames for keep-alive
– Data frames don’t have HTTP overhead
No headers/cookies/security/metadata
– Close frame
Full duplex and bi-directional
WebSocket Protocol Summary
Create WebSocket Endpoints
– Annotation-driven (@ServerEndpoint)
– Interface-driven (Endpoint)
SPI for extensions and data frames
Integration with Java EE Web container
Client and server APIs
Java API for WebSocket Features
Server Side Object Model
WebSocket
@ServerEndpoint(path="/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@OnOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@OnClose
public void onClose(Session peer) {
peers.remove(peer);
}
...
@OnMessage
public void message(String message, Session client) {
for (Session peer : peers) {
peer.getRemote().sendObject(message);
}
}
}
WebSocket Chat Sample
@ServerEndpoint(
value = "/websockets/{id}",
decoders = ShapeCoding.class,
encoders = ShapeCoding.class)
public class DrawingWebSocket { … }
public class ShapeCoding implements Decoder.Text<Drawing.Shape>, Encoder.Text<Drawing.Shape> {
...
@Override
public boolean willDecode(String s) { return true; }
@Override
public Drawing.Shape decode(String s) throws DecodeException { … }
...}
Custom Encoders and Decoders
Standard Java API to help building of RESTful web services and clients
Annotation driven: a DSL for HTTP
POJO-Based Resource Classes
HTTP Centric Programming Model
– Maps HTTP methods to java method invocations
Entity Format Independence
Java API for RESTful Web Services
JAX-RS
Serializar and Deserializer
– MessageBodyReader, MessageBodyWriter
Response object for complex responses
ExceptionMapper for Exception-Mapping
Container Independence
Included in Java EE – for Java EE 7 also in the web profile
Java API for RESTful Web Services
JAX-RS
public class AtmService {
public String balance(String card, String pin) {
return Double.toString (getBalance(card, pin));
}
public Money withdraw(String card,String pin, String amount){
return getMoney(card, pin, amount);
}
...
}
Converting a POJO in a REST Resource
JAX-RS Concepts in an Example
@Path("/atm/{cardId}")
public class AtmService {
@GET @Path ("/balance")
public String balance(String card, String pin) {
return Double.toString (getBalance(card, pin));
}
@POST @Path("/withdrawal")
public Money withdraw(String card, String pin,
String amount){
return getMoney(card, pin, amount);
}
...
}
Converting a POJO in a REST Resource, HTTP method binding
JAX-RS Concepts in an Example
@Path("/atm/{cardId}")
public class AtmService {
@GET @Path ("/balance")
@Produces("text/plain")
public String balance(@PathParam ("cardId") String card,
@QueryParam("pin") String pin) {
return Double.toString (getBalance(card, pin));
}
@POST @Path("/withdrawal")
@Produces("application/json")
public Money withdraw((@PathParam ("cardId") String card,
@QueryParam("pin") String pin,
String amount){
return getMoney(card, pin, amount);
}
...
}
URI Parameter injection, built-in and custom serialization
JAX-RS Concepts in an Example
GET http://[machine]:[port]/[web-context]/atm/3711/balance?pin=1234
POST http://[machine]:[port]/[web-context]/atm/3711/withdrawal?pin=1234
New features
– Client API
– Client and Server Configuration
– Asynchronous processing
– Filters and Interceptors
– Hypermedia support
JAX-RS 2.0
HTML5 Architectural Implications
HTML5 is the new UI across devices
– Applications == HTML5 + JavaScript + CSS3 + Server Resources
Requires a different programming approach
Servers no longer generating markup language
Clients responsible for presentation logic and execution
JavaScript is part of the domain model, JSON is the payload
Event-Driven
No need for browser plugin
The Browser Is the Platform
Thin Server Architecture (TSA) Diagram
JavaScript
HTML
CSS
HT
ML5
DO
M A
PI
User In
terfa
ce
Browser
WebSocket
Server Push
Static
Resource
Services D
ata
Access
RESTful
Data Services
DB
EIS
Web
Storage
Runtime application
presentation
input
display
App download
HTTP
XHR
WebSocket
Server-Sent-Events
App Server
Improved performance
– Caching, no presentation data transmitted again and again
Scalability
– Less data to transfer, session state is on the client
Reduced complexity
– UI control is not split bethween client and server, UI events stay on client
Improved user experience
Offline support only possible with TSA
Advantages
Thin Server Architecture
With Java EE
Thin Server Architecture
Data Sources
HTTP/S
Web
Sockets
SSE
Clients
JA
X-R
S Data Services
JMS
JPA
JAXB
POJO/EJB
Java EE Server
EIS
JSON
XML JCA
WS
En
dp
oin
t
Collaborative drawing
Two-page application
– List of drawings
– Drawing
Demonstrating
– Server-side: JAX-RS, JSON, WebSocket, SSE Java API
– Client-side: JAX-RS, WebSocket, SSE Java and JavaScript API
– JavaFX hybrid Java/HTML5 application
http://github.com/jersey/hol-sse-websocket
Drawing Board Demo
TSA - Architecture
Drawing Board Demo
HTTP/S
Web
Sockets
SSE
Clients
JA
X-R
S/S
SE
Je
rsey
Data Service
GlassFish 4.0
JSON
JSON
DataProvider
POJO
WS
En
dp
oin
t
HTML5 Browser
JavaFX
WebView/WebKit
webSocketSend.send(...)
send(...) onEvent(...)
DrawingService.query(...)
JSON 1.0: Java API for JSON parsing/processing, similar to JAXP
Concurrency Utilities for Java EE 1.0
Java Batch API 1.0
JPA 2.1: Schema generation props, entity graphs and converters, …
Servlet 3.1: Non-blocking IO, Upgrade to WebSocket, …
JTA 1.2: Transactional CDI interceptors, …
CDI 1.1: Ordering of interceptors, Servlet events, …
EJB 3.2: Optional CMP/BMP, Ease-of-use, …
JSF 2.2: @FlowScoped, HTML5 data-* attributes, …
Bean Validation 1.1: method constraints, injectable artifacts, ...
Many other Improvements
Java EE 7 SDK
– With GUI installer for Windows, Linux and Mac OS X
– Web and full profile, english and multi-language
– API docs, tutorial and samples
GlassFish 4.0 OSE with GUI installer or as Zip
Java EE 7 RI binaries and sources for the web and full profile
Maven dependencies and javadocs
– javaee-api-7.0.jar, javaee-web-api-7.0.jar, javaee-api-7.0-javadoc.jar
http://www.oracle.com/technetwork/java/javaee/downloads/index.html
Java EE 7 Implementation Deliverables
https://java.net/downloads/javaee-spec/JavaEE8_Community_Survey_Results.pdf
Java EE Next
JCACHE SSE Configuration
HTML5 ++ Cloud / PaaS
JSON Binding
Java EE 8
and Beyond
NoSQL
https://blogs.oracle.com/ldemichiel/entry/results_from_the_java_ee
Java EE 8 Survey Results
Modular end-to-end TSA-framework for HTML5 applications
Service complonents implemented in JavaScript
– Using a JavaScript runtime based on Nashorn, NodeJS compatible
View components implemented in JavaScript
– Using HTML5 + Widgets + Data Binding with EL
– Minimal JavaScript code needed
avatar.java.net
Project Avatar
Summary
Java SE 8 adds plenty of new features
– At the language, libraries and JVM level
Java SE continues to evolve
– www.jcp.org
– openjdk.java.net/jeps
Java EE continues to evolve
– Java EE 7 is the most exciting of Java EE ever
– GlassFish distributions for Java EE continue to be regularly updated with
major releases of the Java EE specification
– Work on Java EE 8 started