56
Java 7 NormandyJUG Alexis Moussine-Pouchkine Oracle

Java7 normandyjug

Embed Size (px)

Citation preview

Page 1: Java7 normandyjug

Java 7NormandyJUGAlexis Moussine-PouchkineOracle

Page 2: Java7 normandyjug

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

Page 3: Java7 normandyjug

Priorities for the Java Platforms

Grow Developer Base

Grow Adoption

Increase Competitiveness

Adapt to change

Page 4: Java7 normandyjug

A long long time ago...

Page 5: Java7 normandyjug

1.01996WORABouncing

Duke

•••

Page 6: Java7 normandyjug

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

Page 7: Java7 normandyjug

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

5.02004GenericsAnnotations

•••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

62006Perf.JConsole

•••

Page 8: Java7 normandyjug
Page 9: Java7 normandyjug

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

Page 10: Java7 normandyjug
Page 11: Java7 normandyjug

1.11997JDBCJavaBeans

•••

1.32000Hotspot

••

5.02004GenericsAnnotations

•••

72011Project

Coin

••

1.01996WORABouncing

Duke

•••

1.21998CollectionsSwing

•••

1.42002JCPXML

•••

62006Perf.JConsole

•••

Page 12: Java7 normandyjug

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

••

•••

•••

Page 13: Java7 normandyjug

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;

Page 14: Java7 normandyjug

14

String Switch Statement

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

Page 15: Java7 normandyjug

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

Page 16: Java7 normandyjug

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

Page 17: Java7 normandyjug

17

Simplifying Generics

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

Page 18: Java7 normandyjug

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

Page 19: Java7 normandyjug

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

Page 20: Java7 normandyjug

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

Page 21: Java7 normandyjug

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

Page 22: Java7 normandyjug

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

Page 23: Java7 normandyjug

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

Page 24: Java7 normandyjug

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

Page 25: Java7 normandyjug

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

Page 26: Java7 normandyjug

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

••

Page 27: Java7 normandyjug

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

Page 28: Java7 normandyjug

28

Multi-Catch

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

Page 29: Java7 normandyjug

<Insert PictureHere>

DemoProject Coin (with Java EE 6)

Page 30: Java7 normandyjug

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

Page 31: Java7 normandyjug

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

••

•••

••

••

Page 32: Java7 normandyjug

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

Page 33: Java7 normandyjug

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

Page 34: Java7 normandyjug

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

Page 35: Java7 normandyjug

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)

Page 36: Java7 normandyjug

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

Page 37: Java7 normandyjug

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

Page 38: Java7 normandyjug

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

Page 39: Java7 normandyjug

<Insert PictureHere>

DemoFork-Join Framework

Page 40: Java7 normandyjug

Ceylon

KotlinGosu

Fantom

40

invokedynamic

Page 41: Java7 normandyjug

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

•–

••–

••

Page 42: Java7 normandyjug

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

•••••••••

Page 43: Java7 normandyjug

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

•–

•–

•––

•–

Page 44: Java7 normandyjug

44

Page 45: Java7 normandyjug

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

Page 46: Java7 normandyjug

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

Page 47: Java7 normandyjug

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

Page 48: Java7 normandyjug

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

Page 49: Java7 normandyjug

Priorities for the Java Platforms

Grow Developer Base

Grow Adoption

Increase Competitiveness

Adapt to change

Page 50: Java7 normandyjug

Java Communities

Page 51: Java7 normandyjug

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

••

•••

•••

Page 52: Java7 normandyjug

How Java Evolves and Adapts

Community Development of Java Technology

Specifications

Page 53: Java7 normandyjug

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

•••

•••

Page 54: Java7 normandyjug

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

••••

••

••

••

Page 55: Java7 normandyjug

57

Page 56: Java7 normandyjug