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

Post on 10-May-2015

328 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

New features in JavaSE 8. A short introduction.

TRANSCRIPT

Lee Chuk MunnLee Chuk Munnisslcm@nus.edu.sgisslcm@nus.edu.sg

What's New inWhat's New inJavaSE 8?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!

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

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

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

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

LambdaLambda

Computing TodayComputing Today

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

– Utilize the cores

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

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

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;

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

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 !!!

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.

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();

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?

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

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

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

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

Default Default MethodsMethods

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

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...

}}

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();}

}

StreamsStreams

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?

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

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)...

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

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

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

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

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

DemoDemo

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()

JavaScriptJavaScript

this[method_name](x, y);

How do you generate the byte code for the call?

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

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

ProfilesProfiles

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?

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

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

Good Use Cases?Good Use Cases?

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

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

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

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

MiscellaneousMiscellaneous

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) {

...

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

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)

Date TimeDate Time

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

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

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

top related