Java7 normandyjug

Preview:

Citation preview

Java 7NormandyJUGAlexis Moussine-PouchkineOracle

The following is intended to outline our generalproduct direction. It is intended for informationpurposes only, and may not be incorporated intoany contract. It is not a commitment to deliver anymaterial, code, or functionality, and should not berelied upon in making purchasing decisions.

The development, release, and timing of anyfeatures or functionality described for Oracle’sproducts remains at the sole discretion of Oracle.

2

Priorities for the Java Platforms

Grow Developer Base

Grow Adoption

Increase Competitiveness

Adapt to change

A long long time ago...

1.01996WORABouncing

Duke

•••

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

5.02004GenericsAnnotations

•••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

62006Perf.JConsole

•••

9

Evolving the LanguageFrom “Evolving the Java Language” - JavaOne 2005

Java language principlesReading is more important than writingCode should be a joy to readThe language should not hide what is happeningCode should do what it seems to doSimplicity mattersEvery “good” feature adds more “bad” weightSometimes it is best to leave things out

One language: with the same meaning everywhereNo dialects

We will evolve the Java languageBut cautiously, with a long term view“first do no harm”

•–––––––

••

•••

also “Growing a Language” - Guy Steele 1999 “The Feel of Java” - James Gosling 1997

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

5.02004GenericsAnnotations

•••

72011Project

Coin

••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

62006Perf.JConsole

•••

12

Java SE 7 Release ContentsJSR-336: Java SE 7 Release Contents

Java LanguageProject Coin (JSR-334)

Class LibrariesNIO2 (JSR-203)Fork-Join framework, ParallelArray (JSR-166y)

Java Virtual MachineThe DaVinci Machine project (JSR-292)InvokeDynamic bytecode

Miscellaneous enhancements

••

•••

•••

13

Better Integer Literal

Binary literals

With underscores for clarity

int mask = 0b101010101010;

int mask = 0b1010_1010_1010;long big = 9_223_783_036_967_937L;

14

String Switch Statement

Today case label includes integer constants andenum constantsStrings are constants too (immutable)

15

Discriminating Strings Today

int monthNameToDays(String s, int year) {int monthNameToDays(String s, int year) {

if("April".equals(s) || "June".equals(s)if("April".equals(s) || "June".equals(s)|||| "September".equals(s)"September".equals(s)||"November".equals(s))||"November".equals(s)) return 30;return 30;

if("January".equals(s) ||if("January".equals(s) ||"March".equals(s) ||"March".equals(s) || "May".equals(s) ||"May".equals(s) ||"July".equals(s) ||"July".equals(s) || "August".equals(s) ||"August".equals(s) ||"December".equals(s))"December".equals(s)) return 31;return 31;

if("February".equals(s))if("February".equals(s))

16

Strings in Switch Statementsint monthNameToDays(String s, int year) { switch(s) { case "April": case "June": case "September": case "November": return 30;

case "January": case "March": case "May": case "July": case "August": case "December": return 31;

case "February”: ... default: ...

17

Simplifying Generics

Pre-generics List strList = new ArrayList(); List strList = new ArrayList();•

18

Simplifying Generics

Pre-generics List strList = new ArrayList(); List strList = new ArrayList();

With Generics

•ListList<String><String> strList = new ArrayList strList = new ArrayList<String><String>();();

19

Simplifying Generics

Pre-generics List strList = new ArrayList(); List strList = new ArrayList();

With Generics

•ListList<String><String> strList = new ArrayList strList = new ArrayList<String><String>();();ListList<<Map<String, List<String>Map<String, List<String>>> strList = strList = new ArrayList new ArrayList<<Map<String, List<String>Map<String, List<String>>>();();

20

Diamond Operator

Pre-generics List strList = new ArrayList(); List strList = new ArrayList();

With Generics

With diamond (<><>) compiler infers type

ListList<String><String> strList = new ArrayList strList = new ArrayList<String><String>();();ListList<<Map<String, List<String>Map<String, List<String>>> strList = strList = new ArrayList new ArrayList<<Map<String, List<String>Map<String, List<String>>>();();

ListList<String><String> strList = new ArrayList strList = new ArrayList<><>();();ListList<<Map<String, List<String>Map<String, List<String>>> strList = strList = new ArrayList new ArrayList<><>();();

21

Copying a File

InputStream in = new FileInputStream(src);OutputStream out = new FileOutputStream(dest);

byte[] buf = new byte[8192];int n;

while (n = in.read(buf)) >= 0) out.write(buf, 0, n);

22

Copying a File (Better, but wrong)

InputStream in = new FileInputStream(src);OutputStream out = new FileOutputStream(dest);

try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n);} finally { in.close(); out.close();}

23

Copying a File (Correct, but complex)

InputStream in = new FileInputStream(src);try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); }} finally { in.close();}

InputStream in = new FileInputStream(src);try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); }} finally { in.close();}

Copying a File (Correct, but complex)

Exception thrown frompotentially three places.

Details of first two could be lost

25

Automatic Resource Management

try (InputStream in = new FileInputStream(src), OutputStream out = new FileOutputStream(dest)){ byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n);}

26

The Details

Compiler de-sugars try-with-resources into nestedtry-finally blocks with variables to track exception stateSuppressed exceptions are recorded for posterity

using a new facility of ThrowableAPI support in JDK 7

New superinterface java.lang.AutoCloseableAll AutoCloseable and by extensionjava.io.Closeable types useable with try-with-resources

anything with a void close()void close() method is a candidate

JDBC 4.1 retrofitted as AutoCloseableAutoCloseable too

••

27

Exceptions Galoretry { ...} catch(ClassNotFoundException cnfe) { doSomethingClever(cnfe); throw cnfe;} catch(InstantiationException ie) { log(ie); throw ie;} catch(NoSuchMethodException nsme) { log(nsme); throw nsme;} catch(InvocationTargetException ite) { log(ite); throw ite;}

28

Multi-Catch

try { ...} catch (ClassCastException e) { doSomethingClever(e); throw e;} catch(InstantiationException | NoSuchMethodException | InvocationTargetException e) { log(e); throw e;}

<Insert PictureHere>

DemoProject Coin (with Java EE 6)

30

New I/O 2 (NIO2) Libraries

Original Java I/O APIs presented challenges for developers Not designed to be extensibleMany methods do not throw exceptions as expectedrename()rename() method works inconsistentlyDevelopers want greater access to file metadata

Java NIO2 solves these problems

•••••

JSR 203

31

Java NIO2 Features

PathPath is a replacement for FileFileBiggest impact on developers

Better directory supportlist()list() method can stream via iteratorEntries can be filtered using regular expressions in API

Symbolic link supportjava.nio.file.Filesystem

interface to a filesystem (FAT, ZFS, Zip archive, network, etc)

java.nio.file.attributejava.nio.file.attribute packageAccess to file metadata

••

•••

••

••

32

java.nio.file.Path

Equivalent of java.io.Filejava.io.File in the new APIImmutable

Have methods to access and manipulate PathPath

Few ways to create a PathPathFrom PathsPaths and FileSystemFileSystem

•–

•–

//Make a reference to the path//Make a reference to the pathPath home = Paths.get("/home/fred");Path home = Paths.get("/home/fred");

//Resolve tmp from /home/fred -> /home/fred/tmp//Resolve tmp from /home/fred -> /home/fred/tmpPath tmpPath = home.resolve("tmp");Path tmpPath = home.resolve("tmp");

//Create a relative path from tmp -> ..//Create a relative path from tmp -> ..Path relativePath = tmpPath.relativize(home)Path relativePath = tmpPath.relativize(home)

File file = relativePath.toFile();File file = relativePath.toFile();

33

File Operation – Copy, Move

File copy is really easyWith fine grain control

File move is supportedOptional atomic move supported

•–

•–

Path src = Paths.get("/home/fred/readme.txt");Path src = Paths.get("/home/fred/readme.txt");Path dst = Paths.get("/home/fred/copy_readme.txt");Path dst = Paths.get("/home/fred/copy_readme.txt");

Files.copy(src, dst,Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES,StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);StandardCopyOption.REPLACE_EXISTING);

Path src = Paths.get("/home/fred/readme.txt");Path src = Paths.get("/home/fred/readme.txt");Path dst = Paths.get("/home/fred/readme.1st");Path dst = Paths.get("/home/fred/readme.1st");Files.move(src, dst,Files.move(src, dst,StandardCopyOption.ATOMIC_MOVE);StandardCopyOption.ATOMIC_MOVE);

34

Directories

DirectoryStream iterate over entriesScales to large directoriesUses less resourcesSmooth out response time for remote file systemsImplements IterableIterable and CloseableCloseable for productivity

Filtering supportBuild-in support for glob, regex and custom filters

•––––

•–

Path srcPath = Paths.get("/home/fred/src");Path srcPath = Paths.get("/home/fred/src");

try (DirectoryStream<Path> dir = try (DirectoryStream<Path> dir = srcPath.newDirectoryStream("*.java")) {srcPath.newDirectoryStream("*.java")) { for (Path file: dir)for (Path file: dir) System.out.println(file.getName());System.out.println(file.getName());}}

35

Concurrency and Collections Updates - JSR 166y

1970 1975 1980 1985 1990 1995 2000 2005 2010

1

10

100

1,000

10,000

1,000,000

100,000

10,000000

Clock (MHz)

Transistors(1,000s)

36

ForkJoin Framework

Goal is to take advantage of multiple processorDesigned for task that can be broken down into

smaller piecesEg. Fibonacci number fib(10) = fib(9) + fib(8)

Nearly always recursiveProbably not efficient unless it is

•–

if I can manage the taskif I can manage the task perform the taskperform the taskelseelse fork task into fork task into xx number of smaller/similar number of smaller/similartasktask join the resultsjoin the results

37

ForkJoin Example – Fibonacci

public class Fibonacci extends public class Fibonacci extends RecursiveTask<RecursiveTask<IntegerInteger>> { { private final int number; private final int number; public Fibonacci(int n) { number = n; } public Fibonacci(int n) { number = n; }

@Override protected @Override protected IntegerInteger compute() { compute() { switch (number) { switch (number) { case 0: return (0); case 0: return (0); case 1: return (1); case 1: return (1); default: default: FibonacciFibonaccif1 = new Fibonacci(number – 1);f1 = new Fibonacci(number – 1); FibonacciFibonaccif2 = new Fibonacci(number – 2);f2 = new Fibonacci(number – 2); f1.fork(); f2.fork(); f1.fork(); f2.fork(); return (f1.join() + f2.join()); return (f1.join() + f2.join()); } } } }}}

38

ForkJoin Example – Fibonacci

ForkJoinPool pool = new ForkJoinPool();ForkJoinPool pool = new ForkJoinPool();Fibonacci r = new Fibonacci(10);Fibonacci r = new Fibonacci(10);pool.submit(r);pool.submit(r);

while (!r.isDone()) {while (!r.isDone()) { //Do some work //Do some work ......}}

System.out.println("Result of fib(10) =System.out.println("Result of fib(10) ="+r.get());"+r.get());

<Insert PictureHere>

DemoFork-Join Framework

Ceylon

KotlinGosu

Fantom

40

invokedynamic

41

InvokeDynamic Bytecode

JVM currently has four ways to invoke methodInvokevirtual, invokeinterface, invokestatic, invokespecial

All require full method signature dataInvokeDynamic will use method handle

Effectively an indirect pointer to the method

When dynamic method is first called bootstrap codedetermines method and creates handleSubsequent calls simply reference defined handleType changes force a re-compute of the method

location and an update to the handleMethod call changes are invisible to calling code

•–

••–

••

42

Miscellaneous enhancements

JDBC 4.1, RowSet 1.1Security: Elliptic curve cryptography, TLS 1.2Unicode 6JAXP 1.4.4, JAX-WS 2.2, JAXB 2.2Swing: Nimbus L&F, JXLayer, HW accelerationsClassLoader architecture changesclose()close() for URLClassLoaderJavadoc support for CSSNew Objects class

•••••••••

43

Other EnhancementsClient & Graphics

Added Nimbus L&F to the standardMuch better –modern- look than what was previously available

Platform APIs for Java 6u10 Graphics FeaturesShaped and translucent windows

JXLayer core included in the standardFormerly SwingLabs componentAllows easier layering inside of a component

Optimized Java2D Rendering Pipeline for X-WindowsAllows hardware accelerated remote X

•–

•–

•––

•–

44

Java 7 : Available today!

Plan "B" - Sept. 2010JSR approved - Dec. 2010Java 7 Launch - 07/07JSR Final Approval Ballots

JavaSE 8 passed with 15 YES, 1 NO (Google) votesProject Coin passed with 16 YES votesNIO2 passed with 16 YES votesInvokeDynamic passed with 16 YES votes

Java SE 7 Reference Implementation (RI)Java 7 Oracle SDK on July 28th 2011...Java 7 updates

••••

••••

••••

You arehere

Oracle JDK 7 Updates

Support for Apple's Mac OS XUse OpenJDK for the time being (easy)

Expect several JDK 7 update releasesMore platform supportImproved performanceBug fixesRegular HotRockit* progress

remove PermGen (yay!)large heaps with reasonable, then predictable latencies serviceability improvements ported over to HotSpot from

JRockitJRockit Mission ControlJRockit Flight Controler

••

•••••

•••

••

*: tentative name for the HotSpot/JRockit converged JVM

47

More Project CoinSmall Language Changes

Project Lambda (JSR 335)Closures and lambda expressions

Project Jigsaw (JSR-294)Modularizing the Java Platform

Java SE 8

More about Java 8

More Content :Annotations on Java types (JSR 308)Wish List * :

Serialization fixesMulticast improvementsJava APIs for accessing location, compass and other ”environmental” data (partially exists in ME)Improved language interopFaster startup/warmupDependency injection (JSR 330)Include select enhancements from Google GuavaSmall Swing enhancementsMore security/crypto features, improved support for x.509-style certificates etcInternationalization: non-Gregorian calendars, more configurable sortingDate and Time (JSR 310)Process control API

ScheduleLate 2012 (planning in progress)

•••

••••••••••••

••

*: a good number will NOT make the list

Priorities for the Java Platforms

Grow Developer Base

Grow Adoption

Increase Competitiveness

Adapt to change

Java Communities

Free and Open Source Software (FOSS)Open to all

Corporate contributors: Oracle, RedHat, IBM, Apple, SAPKey individual contributorsRatified By-laws

Serves as the JavaSE reference implementation (RI)Where java.next is being developedhttp://openjdk.org

••

•••

•••

How Java Evolves and Adapts

Community Development of Java Technology

Specifications

JCP Reforms

Developers voice in the Executive CommitteesSOUJavaLondon JavaCommunity

JCP starting a program of reformJSR 348: Towards a new version of the JCP (JCP.next)First of two JSRs to update the JCP itself

•••

•••

55

Conclusions

Java SE 7Incremental changesEvolutionary, not revolutionaryGood solid set of features to make developers life easier

OpenJDK as a thriving open source projectJava SE 8

Major new features: Modularization and ClosuresMore smaller features to be defined

Java continues to grow and adapt to the challengesCommunity play required

••••

••

••

••

57

Recommended