nus hackers club mar 21 - whats new in javase 8?

52
Lee Chuk Munn Lee Chuk Munn [email protected] [email protected] What's New in What's New in JavaSE 8? JavaSE 8?

Upload: chukmunnlee

Post on 10-May-2015

328 views

Category:

Technology


2 download

DESCRIPTION

New features in JavaSE 8. A short introduction.

TRANSCRIPT

Page 1: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Lee Chuk MunnLee Chuk [email protected]@nus.edu.sg

What's New inWhat's New inJavaSE 8?JavaSE 8?

Page 2: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

JavaSE TimelineJavaSE Timeline

JDK 1.0 Jan 1996

JDK 1.1 Feb 1997

JDK 1.2 Dec 1998

JDK 1.3 May 2000

JDK 1.4 Dec 2002

JDK 5 Sept 2004

JDK 6 Dec 2006

JDK 7 July 2011

JDK 8 Mar 2014

5 years!

Page 3: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

What Happened?What Happened?

● Very ambitious– Modularity

● Refactor the JDK● Native packaging

– Lambda ● Language and libraries● Lots of competing design

– New bytecode to support dynamic languages– Lots of other proposed features

● Too many moving parts

Page 4: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Java SE 7/SE 8Java SE 7/SE 8

● Oracle acquired Sun in 2010● JavaSE 7 gestation period was too long

– Developers are loosing interest● Parts of the JDK was done, some was not

– Eg invokedynamic was quite solid, closures were not● Took a poll

– Deliver it in 2 parts and what is completed sooner– Or wait for everything to complete – longer

Page 5: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

JavaSE 7JavaSE 7

● Released on July 28 2011● Features

– Project Coin – small change● Integer literals, Strings in switch, type inferencing <>● Multi-catch/precise rethrow● Try-with-resources

– NIO2● Paths, filesystem support, file attributes and permissions● Async I/O, file system walker, filesystem watcher

– Fork/join framework– invokedynamic

Page 6: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Modernizing the Java PlatformModernizing the Java Platform

● Biggest change on the Java platform since JavaSE 5– Change the way we write Java applications

● Language– Lambda expressions– Interface evolution

● Libraries– Bulk data operations on Collections

● Platform– Profiles

Page 7: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

LambdaLambda

Page 8: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Computing TodayComputing Today

● Multicore is now the default● Need to make writing parallel code easier● Need to make libraries smarter

– Utilize the cores

Page 9: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Concurrency in JavaConcurrency in Java

● JDK 1.x – java.lang.Thread ● JDK 1.5 – java.util.concurrent

– Locks, semaphores, Atomics– Callables– Synchronization data structures – cyclic barrier,

count down latches, etc● JDK 1.7 – Fork/join framework

Page 10: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

What's the IssueWhat's the Issue

● Preference for doing things in libraries vs doing things in the language

● Decent job of providing easy to use parallel libraries ● Need to reduce conceptual and syntactic gap

between serial and parallel– Serial and parallel code for a given task looks very

different● Need language changes to better support the libaries

Page 11: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Student with the Highest ScoreStudent with the Highest Score

Collection<Student> students = …

double highestScore = 0.0;

for (Student s : students)if ((s.gradYear == 2013)

&& (s.score > highestScore))highestScore = s.score;

Page 12: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Student with the Highest ScoreStudent with the Highest ScoreCollection<Student> students = ...double highestScore = 0.0;for (Student s : students) {if ((s.gradYear == 2013)

&& (s.score > highestScore))highestScore = s.score;

}

● Code is inherently serial– Iterate through students serially– Stateful – use of highestScore

● Client determines how to iterate the collection– Not the collection

Page 13: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Using Functional Language StyleUsing Functional Language Style

HypotheticalCollection student = … double highestScore = student

.filter(new Predicate<Student>() {public boolean op(Student s) {

return (s.getGraduateYear() == 2013); }}).map(new Mapper<Student, Double>() {

public double extract(Student s) {return (s.getScore()); }

}).max();

Stateless functions and immutable data

But syntactically ugly !!!

Page 14: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

What is Closure?What is Closure?

function adder(x) {return (function(y) {return (x + y);

});}

var addTo3 = adder(3);Var addTo7 = adder(7);console.log(addTo3(5) + addTo7(5)); → 21

A function together with a referencing environment for the non local (free variable) variables of the function. Once defined, the free variables are bound to the function, or “closes over” it.

Page 15: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Lambda Expressions in JavaLambda Expressions in Java

● Lambda expressions are anonymous functions– Like a method, has a typed argument list, a return

type, a set of thrown exceptions, a body– Body can be an expression or a block

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

Page 16: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Lambda TypesLambda Types

● SAM – Single Abstract Method– Annotated with @FunctionalInterface

● Not necessary, like @Override

– Ensures that the functional interface contract is honoured

.map((Student s) -> s.getScore())

What is this type?

Page 17: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

ExampleExample

File srcDir = new File(“/home/cmlee/src”);

for (File f: srcDir.listFiles((File sf) -> sf.getName().endsWith(“.java”))

//Do something with f

FileFilter.accept(File f) returns boolen

Page 18: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Target TypingTarget Typing

File srcDir = new File(“/home/cmlee/src”);

for (File f: srcDir.listFiles((File sf) -> sf.getName().endsWith(“.java”))

//Do something with f

FileFilter.accept(File f) returns boolen

File srcDir = new File(“/home/cmlee/src”);

for (File f: srcDir.listFiles(sf -> sf.getName().endsWith(“.java”))

//Do something with f

Simplified toTarget typing – inferring the Lambda expression type

Page 19: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Target TypingTarget Typing

● Same lambda expression can be assigned to different SAM

FileFilter fileFilter = f -> f.getName().endsWith(“.java”);

DirectoryStream.Filter<File> directoryFilter = f -> f.getName().endsWith(“.java”);

Lambda literal

Page 20: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Method ReferenceMethod Reference

● Reuse a method as a Lambda expression– Does not have to be static– Use :: to reference it

File srcDir = new File(“/home/cmlee/src”);

for (File f: srcDir.listFiles(File::canRead) {//Do something with f

Page 21: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Default Default MethodsMethods

Page 22: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

InterfacesInterfaces

● Methods in interfaces are cast in stone– If you do, you break backward compatibility– Classes need to be recompiled

● If you cannot change an interface you cannot refactor

● Issue with evolving libraries that are based on interfaces– Eg java.util.List, java.util.ListEx, java.util.ListEx2

Page 23: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Default MethodsDefault Methods

● New methods with default implementation to existing interfaces– Without recompiling the implementation class

● New implementation can decide if they want to reimplement the default methods– “Mirandarizing” the implementation

package java.util;public interface List<T> {

//Existing methods......default public void sort(Comparator<? super T> cmp) {

//Sort the list...

}}

Page 24: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Benefits of Default MethodsBenefits of Default Methods

● Retrofitting existing API with newer capabilities– Enumeration have been superseded by Iteratorinterface Enumeration<E> extends Iterator<E> {

//Existing Enumeration methodsboolean hasMoreElements();E nextElement();//Methods from Iteratordefault boolean hasNext() {

return (hasMoreElements());}default E next() {

return (nextElement());}default void remove() {

throw new UnsupportedOperationException();}

}

Page 25: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

StreamsStreams

Page 26: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

CollectionsCollections

● Collections are data structure– List, Set, Queue, Stack– Size of data is fixed at the point of using it

● Operations on collections can potentially mutate the state of the collection– Not thread friendly– Eg. remove()

● Values cannot be lazily generated– How do you represent and random set of positive numbers?

Page 27: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

What are Streams?What are Streams?

● Conduit for data flow● As the data are flowing, perform operation on

them● Streams are composable

– Combine one stream with anohter● Does not modify the source

Page 28: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Creating StreamsCreating Streams

● Explicitly

● From collections

● From suppliers/generators

Stream.of(new int[] {0, 1, 2, 3, 4, 5, 6});

List<Integer> intList = new LinkedList<>();//Initialize int list...intList.stream();

final Random rand = new Random();Stream.of(()-> rand.nextInt());

IntStream.generate(() → rand.nextInt())...LongStream.range(0, 1000L)...

Page 29: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Streams ExampleStreams Example

Set<Student> students = …

for (Student s: students)System.out.println(“Name: %s, Email: %s”

, s.getName(), s.getEmail());

students.stream().forEach(s -> {System.out.println(“Name: %s, Email: %s”

, s.getName(), s.getEmail());});

Refactor to

Page 30: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Streams ExampleStreams Example

Set<Student> students = …students.stream()

.filter(s -> (2013 == s.getGradYear())&& (s.getScore() > 90))

.findAny() //Returns Optional

.ifPresent(s -> {System.out.println(s);

})

Print out the names of all honor students for 2013

LINQ like DSL

Page 31: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

JavaScriptJavaScript(and dynamic language support)(and dynamic language support)

Page 32: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Dynamic Language SupportDynamic Language Support

● http://www.is-research.de/info/vmlanguages/category/jvm-language/– Some are academic, experimentation– You can find a Java implementation form MOST

dynamic/scripting languages – prefix with j● JavaScript, Lua, Python, Haskell, Scheme,...

– Some are JVM specific● Scala, Groovy, Clojure

– Some in serious use● Scala, JRuby, Groovy, Clojure

Page 33: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Java Virtual MachineJava Virtual Machine

● Reasons for targeting the JVM– Java language != Java Virtual Machine– Mature, performant, scalable, introspection, ubiquitous

● Dynamic language support began in JDK 6 ● Integration with Java ecosystem

– Large set of libraries● Use cases

– Java calling into script – adding scripting capabilities to Java application

– Script calling into Java – prototyping

Page 34: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

DemoDemo

Page 35: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Scripting ExampleScripting Example

config.js

ScriptEngine jsEngine =mgr.getEngineByName(“JavaScript”);

//Application configuration beanMyAppConfig appConfig = new MyAppConfig();//Bind appConfig to configjsEngine.put(“config”, appConfig);jsEngine.eval(new FileReader(“confing.js”));

config.server = “myserver”config.port = 12345//Dynamically determine timeoutconfig.timeout = calculateTimeout()

Page 36: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

JavaScriptJavaScript

this[method_name](x, y);

How do you generate the byte code for the call?

Page 37: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

invokedynamicinvokedynamic

this[method_name](x, y)

invokedynamic [#bootstrapMethod] .this_method_name

class LangaugeRuntime {bootstrapMethod(info) {

...return new CallSite();

}

class AClass {aMethod(x, y) {

...}

CallSite

MethodHandle

1. Invoke bootstrap

2. Produces CallSite

3.Complete linkage

4. Invokes method implementation

Page 38: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

NashornNashorn

● A new Javascript engine based on invokedynamic– To supercede Rhino in JavaSE 8

● Why?– Node.js on Java? - https://avatar-js.java.net– Javascript container ala PhoneGap/Cordova, Adobe AIR

● Side note: javafx.scene.web.WebView– Wrapper for WebKit– Now you can display HTML pages (with JavaScript)

correctly in Java

Page 39: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

ProfilesProfiles

Page 40: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

The Java RuntimeThe Java Runtime

● The JDK is big and monolithic– Lots of improvement over the years: warm start, memory images

● Slow startup time, memory footprint– Why should the VM load javax.swing.Jframe when you are just

using classes from java.lang package?● Single codebase – simplify engineering, better code quality

– From small to big– Not the case: CLDC, CDC, JavaSE

● Versioning?

Page 41: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Compact ProfilesCompact Profiles

● A step toward full modularization– Coming in JavaSE 9 (I hope)

● Enable applications that use only a subset of the JavaSE platform on resource constrained devices– Eg. CLDC, CDC

● Profiles – The entire JVM and the JLS spec– Define a subset of the API– Larger profiles must be superset of smaller ones– The contents of the API packages must be the same as the full SE

platform

Page 42: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Compact ProfilesCompact Profiles

● compact1 – 14MB

– Smallest set of API packages – 14MB – java.lang, java.nio, java.util, java.net, java.security

● compact2 – 18MB

– compact1 + XML + RMI + JDBC

● compact3 – 21MB– compact2 + everything except Desktop, JAX-WS/JAXB, CORBA

● Full SE – 45MB● See

https://blogs.oracle.com/jtc/entry/a_first_look_at_compact

Page 43: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Good Use Cases?Good Use Cases?

Linux X86Linux ARM soft floatLinux ARM VFP soft floatLinux ARM VFP hard floatLinux PowerPCLinux PowerPC e500v2

Page 44: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Compact Profile ToolsCompact Profile Tools

● Restricting compiles to a profile

● Analyzing compact dependency

$ jdeps -P Hello.class

Hello.class -> /opt/java/jdk1.8.0/jre/lib/rt.jar (compact1)

<unnamed> (Hello.class)

-> java.io compact1

-> java.lang compact1

$ javac -profile compact1 Hello.class

Page 45: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Use The Docs Luke...Use The Docs Luke...

Page 46: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Embedded JavaEmbedded Java

● Can be downloaded from Oracle website● Commercial product

Prebuild profilesejdk1.8.0ejdk1.8.0/{architecture}ejdk1.8.0/{architecture}/compact1ejdk1.8.0/{architecture}/compact2ejdk1.8.0/{architecture}/compact3ejdk1.8.0/{architecture}/jreejdk1.8.0/{architecture}/extensions

Custom profilesejdk1.8.0/bin/jrecreate.sh

Page 47: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

MiscellaneousMiscellaneous

Page 48: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Parameter NamesParameter Names

● Reflection now returns parameter names● Good news for all tools and framework

developers● Hypothetical example from JAX-RS

@GET @Path(“{custId}”)public void get(@PathParam(“custId”) int custId) {

...

@GET @Path(“{custId}”)public void get(@PathParam int custId) {

...

Page 49: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

AnnotationAnnotation

● Annotations are pieces of information embedded in the class files– Typically used by tools to generate code, enforce certain

programming practices, etc● Processed during

– Compile time– At runtime

● You can annotate– Package, class, member, constructor, method, parameters,

local variable, annotation

Page 50: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Type AnnotationType Annotation

● Annotations can currently be used on type declarations– Package, class, member, constructor, method, parameters,

local variable, annotation● Annotations can now be used on where types are used

– Permits error detection by pluggable type checkers– See http://types.cs.washington.edu/checker-framework

List<@Email String> emails = new @ReadOnly LinkedList<String>(aCollection);

if ((@NonNull)obj) instanceof String)

Page 51: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?

Date TimeDate Time

LocalDate yesterday =LocalDate.now().minusDays(1);

ZoneId.getAvailableZoneIds().stream().forEach(tz -> {

System.out.println(tz);});

Page 52: NUS Hackers Club Mar 21 - Whats New in JavaSE 8?