Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Â
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
1. Lee Chuk MunnLee Chuk Munn
isslcm@nus.edu.sgisslcm@nus.edu.sg
What's New inWhat's New in
JavaSE 8?JavaSE 8?
2. 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!
3. 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
4. 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
5. 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
6. 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
9. 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
10. 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
11. 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;
12. 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;
}
â
Code is inherently serial
â Iterate through students serially
â Stateful â use of highestScore
â
Client determines how to iterate the collection
â Not the collection
13. 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 !!!
14. 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.
15. 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();
16. 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?
17. 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
18. 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 to
Target typing â inferring the
Lambda expression type
19. 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
20. 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
22. 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
23. 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
...
}
}
24. Benefits of Default MethodsBenefits of Default Methods
â
Retrofitting existing API with newer capabilities
â Enumeration have been superseded by Iterator
interface Enumeration<E> extends Iterator<E> {
//Existing Enumeration methods
boolean hasMoreElements();
E nextElement();
//Methods from Iterator
default boolean hasNext() {
return (hasMoreElements());
}
default E next() {
return (nextElement());
}
default void remove() {
throw new UnsupportedOperationException();
}
}
26. 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?
27. 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
28. 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)...
29. 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
30. 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
32. 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
33. 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
38. 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
40. 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?
41. 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
42. 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
43. Good Use Cases?Good Use Cases?
Linux X86
Linux ARM soft float
Linux ARM VFP soft float
Linux ARM VFP hard float
Linux PowerPC
Linux PowerPC e500v2
48. 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) {
...
49. 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
50. 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)
51. Date TimeDate Time
LocalDate yesterday =
LocalDate.now().minusDays(1);
ZoneId.getAvailableZoneIds().stream()
.forEach(tz -> {
System.out.println(tz);
});