Top Banner
Java 8 - New Features Naveen Hegde Apr 2014
27
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java SE 8 - New Features

Java 8 - New Features

Naveen HegdeApr 2014

Page 2: Java SE 8 - New Features

Java Version History

2

1996 1998 2000 2002 2004 2006 2011

Java SE 8Spider

2014

First release developed under the Java Community Process

Version 1.5 -> 5To reflect level of Maturity, Stability

J2SE -> Java SEDropped .0

Page 3: Java SE 8 - New Features

• Java 5– Generics, Autoboxing

– Enhanced For-Loop, VarArgs and more…

Recap - Major Feature Additions in Java

3

Java 6• Script Engine

• New I/O

• Jconsole, profiler & debug interface (JVMPI, JVMDI)

Java 7• Strings in Switch, Catch Multiple-Exceptions

• Try-with-Resource, Type Interface

• JVM Support for Non-Java Languages

Page 4: Java SE 8 - New Features

• Lambda Expressions

• Streams Facility

• Date-Time Library

• permgen replaced by Metaspace

• Type Annotations and Repeating Annotations

• jdbc-odbc bridge removed

• New utilities to improve Performance, Scalability

Java SE 8 New Features at glance

4

Page 5: Java SE 8 - New Features

• Treat functionality as method argument (code as data)

• Avoid anonymous inner class which seem excessive & unclear

• Cleaner way to implement Functional Interfaces

• Used to create anonymous methods

Lambda Expressions

5

Parameter(s)Body

single expression or statement block

Lambda Expression Syntax

Sample Code for “Sorting persons array by Age”

Java compiler determines Lambda Expr Type using new “Target Typing” mechanism

Page 6: Java SE 8 - New Features

• In Swing, JavaFX, Often, event handler interfaces are functional interfaces

• Lambda expressions can best replace anonymous classes created for keyboard actions, mouse actions etc

Using Lambda Expression in GUI

6

Page 7: Java SE 8 - New Features

• Creation of compact, easy-to-read lambda expressions

• Use it with Lambda Expresions for – Encapsulate a single unit of behavior and pass it to other code

– Create simple instance of a functional interface

Method References

7

Method Reference Type Example

to a static method Person::compareByAge

to an instance method of a particular object myComparator::compareByName

to a method of arbitrary type instance String::compareToIgnoreCase

to a constructor HashSet::new

Page 8: Java SE 8 - New Features

• Ability to add default implementation in interfaces

• No impact on already existing implementations

Default Interface Method

8

Extending Interfaces That Contain Default Methods • Not mention default method -> inherits the default

• Redeclare the default method -> makes it abstract.

• Redefine the default method -> overrides it

Interface with all default methods is like an Adapter

Page 9: Java SE 8 - New Features

• New package for filter/map/reduce transformations on streams

• Includes many useful built in aggregate operations

java.util.stream.*

9

int ave = Arrays.stream(personArr) .filter(b -> b.getGender() == Gender.MALE) .mapToDouble(Person::getSalary).average()

.getAsDouble();‘persons’ is a Collection<Person>

Generating Streams• Collection objects: via the stream() and parallelStream() methods

• Array elements: via Arrays.stream(Object[])

• Lines of File : BufferedReader.lines()

• Streams of random numbers : Random.ints()

Page 10: Java SE 8 - New Features

• No storage– A stream is not a data structure that stores elements

– it conveys elements from a source (Array,Collection,IO Channel etc) through a pipeline of computational operations

– stream operation produces a result without modifing its source

• Functional in nature– Enable Functional way of Working with Databases – Easy and elegant

• Parallelism– Streams facilitate parallel execution by reframing the computation as a

pipeline of aggregate operations

• Consumable– The elements are visited only once during the life of a stream.

– new stream must be generated to revisit the same elements

Why use Streams?

10

Page 11: Java SE 8 - New Features

• JavaSE 6 – Date

– Calendar

– DateFormat

– TimeZone

Date-Time Packages

11

Java 8

formatter=DateTimeFormatter.ofPattern("yyyy MM dd");

String text = date.toString(formatter);

LocalDate date = LocalDate.parse(text, formatter)

ChronoUnit.DAYS.between(t1, t2)

Page 12: Java SE 8 - New Features

• Motive– Solve the common scalability problem of “Maintaining a single count, sum,

etc. that is updated by many threads”

• How?– Internally employ contention-reduction techniques

– Provides huge throughput improvements as compared to Atomic variables

• Classes– DoubleAccumulator

One or more variables that together maintain a running double value updated using a supplied function.

– DoubleAdder One or more variables that together maintain an initially zero double sum.

– LongAccumulator

– LongAdder

Scalable-Updatable variable support

12

Page 13: Java SE 8 - New Features

• Streams & Lambda expression based new methods– forEach methods

forEach, forEachKey, forEachValue, and forEachEntry

– search methods

search, searchKeys, searchValues, and searchEntries

– reduction methods

reduce, reduceToDouble, reduceToLong …

ConcurrentHashMap Enhancements

13

-> ConcurrentHashMaps (and classes built from them) are more useful as cache

Page 14: Java SE 8 - New Features

• Interfaces– CompletionStage<T>: A stage of a possibly asynchronous computation

• Classes– CompletableFuture<T>: A Future that may be explicitly completed

May be used as a CompletionStage,

Supports actions that trigger upon its completion

– CountedCompleter<T>: A ForkJoinTask with a completion Action

Action is triggered when there are no remaining pending actions

– ConcurrentHashMap.KeySetView<K,V>:

A view of ConcurrentHashMap as a Set of keys

Additions may optionally be enabled by mapping to a common value

New Additions to java.util.concurrent

14

Page 15: Java SE 8 - New Features

• Arrays.parallelSort()– Parallel merge-sort algorithm technique using ForkJoinPool

• Bulk Data Operations for Collections

• Base64 Encoding & Decoding support– New Classes

Base64, Base64.Decoder, Base64.Encoder

– Eg Applications of use

Multipurpose Internet Mail Extensions (MIME)

encode passwords for HTTP headers

Utils

15

Page 16: Java SE 8 - New Features

• StampedLock– A capability-based lock with three modes for controlling access

1) Reading 2) Writing 3) Optimistic Reading

– Lock acquisition methods return a stamp

– Stamp represents and controls access with respect to a lock state

– Designed for the development of thread-safe components

– Not re-entrant

• ForkJoinPool (since java7)– ExecutorService for running ForkJoinTasks

– A static commonPool() is added to reduce resource usage Default pool appropriate for most applications

– ForkJoinPool differs from other kinds of ExecutorService Mainly by virtue of employing work-stealing

All threads in the pool attempt to find and execute subtasks created by other tasks or external clients like management and monitoring operations

Miscellaneous

16

Page 17: Java SE 8 - New Features

• Repeating Annotations– provide the ability to apply the same annotation type more than once to

the same declaration

• Type Annotations– provide the ability to apply an annotation anywhere a type is used, not

just on a declaration.

– Used with a pluggable type system,

– this feature enables improved type checking of your code

Annotations

17

Page 18: Java SE 8 - New Features

• Motive– Eliminate need for ‘MaxPermSize’ tuning (one of the reasons for OOM error)– Improve GC performance

• Removal of PermGen– Most allocations for the class metadata is done out of native memory

– Some miscellaneous data has been moved to the Java heap

– klasses that were used to described class metadata have been removed – Metaspace is Non-contigeous to heap

– A garbage collection may be induced to collect dead classloaders and classes. The first garbage collection will be induced when the class metadata usage reaches MaxMetaspaceSize

PermGen replaced by Metaspace

18

HeapNewGen

Survivor Space

OldGen

PermGen

HeapNewGen

Survivor Space

OldGen

Metaspace Native Mem

PermGen=Region{Class Metadata, Hierarchy info, Constant Pool, Bytecode …}

No more “OutOfMemoryError: PermGen space”

Page 19: Java SE 8 - New Features

• Defines subsets of JRE for devices that have limited storage capacity

• Match Application Functional needs closely

Compact Profiles

19

Security(E) JMX Instrumentation XML JAXP (E)

JDBC RMI XML JAXP

Core Networking IO Collections

Scripting Regex JNDI Reflection

Pro

file

1

Pro

file

2

Co

mp

act

Pro

file

3

Full

SE A

PI Swing Beans Sound Image I/O Java 2D

CORBA JNI IDL Print Service AWT

Page 20: Java SE 8 - New Features

• Lightweight, high-performance script engine

• Implemented in Java by Oracle

• Replaces Mozilla Rhino JavaScript interpreter– Rhino compiled all JavaScript code to bytecode in generated class files.

– Compared to C implementation of Javascript run with JIT compilation, Rhino had better performance

– Rhino had memory leak since most JVMs don’t clean unused classes

• Nashorn– compiles scripts in memory and passes bytecode directly to JVM

Nashorn Javascript Engine

20

Page 21: Java SE 8 - New Features

• Enriched 3D Graphics features

• New SwingNode class– SwingNode - enables embedding Swing content into JavaFX

– ScheduledService - allows to automatically restart the service

• Enhanced text support– Hindi and Thai controls

– New Styles - bi-directional text, multi-line etc

• Now Compatible with ARM platforms

Java FX

21

Page 22: Java SE 8 - New Features

• The JDBC-ODBC Bridge has been removed– Reason

The JDBC-ODBC Bridge had been non-supported product

Was provided with only selected JDKs and not included in JRE

– Alternate recommendation

Use a JDBC driver provided by the database vendor

If it was in use to with MS Access DB or Excel spreadsheet etc, could be replaced by pure java DB like H2, Java DB etc.

• JDBC 4.2– Minor enhancements to JDBC to improve usability and portability

• JDK 8 includes Java DB 10.10– a version of the Apache Derby database (since Java 5)

JDBC

22

Page 23: Java SE 8 - New Features

• URLPermission Represents permission to access– a resource defined by url– for a given set of user-settable request methods and request headers

• URLPermission(String url_name, String actions)– name of the permission is the url string

http://www.oracle.com/a/b/*

– actions string is a concatenation of the request methods and headers "POST,GET,DELETE“

"POST,GET:Header1,Header2“

• Examples of Path Matching – public boolean implies(Permission p)

HTTP URL Permission

23

This’s path P’s path Matches /implies

/a/b/* /a/b/c Yes

/a/b/* /a/b/c/d No

/a/b/- /a/b/c/d/e Yes

Page 24: Java SE 8 - New Features

• KeyStore enhancements– new Domain KeyStore type java.security.DomainLoadStoreParameter

– new command option - importpassword for the keytool utility

• New variant of AccessController.doPrivileged– enables code to assert a subset of its privileges, without preventing the

full traversal of the stack to check for other permissions

• Support for– Stronger algorithms for password-based encryption

– AEAD algorithms

– SHA-224 Message Digests

– rcache Types in Kerberos 5 Replay Caching

Security

24

Page 25: Java SE 8 - New Features

• Leverage CPU Instructions for AES Cryptography – Intel Westmere hardware (2010 or newer) has instruction set to

support AES (Advanced Encryption Standard)

– Syntax: -XX:+UseAES -XX:+UseAESIntrinsics

• JMC 5.3– JMC (Originally developed by JRockit) is an advanced set of tools that

enabling efficient JVM monitoring & profiling

– JMC is bundled with the HotSpot JVM starting from Java SE 7u40

HotSpot VM

25

Page 26: Java SE 8 - New Features

• New Commands– Jjs – invoke Nashorn java script engine

– Java – can launch JavaFX

– Jdeps - analyze class files

• Pack200 – Pack200 support for Constant Pool Entries and New Bytecodes

Tools

26

Page 27: Java SE 8 - New Features

Thank You

END

27