Java 7 New Features Nakov EGJUG Cairo 2 May 2010

download Java 7 New Features Nakov EGJUG Cairo 2 May 2010

of 120

Transcript of Java 7 New Features Nakov EGJUG Cairo 2 May 2010

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    1/120

    Java 7Java 7 New FeaturesNew Features

    Svetlin NakovSvetlin NakovBulgarian Association of Software DevelopersBulgarian Association of Software Developers

    www.devbg.orgwww.devbg.orgEgyptian Java User Group (EGJUG)

    Cairo, 2 May 2010

    Egyptian Java User Group (EGJUG)

    Cairo, 2 May 2010

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    2/120

    About the SpeakerAbout the Speaker

    Svetlin NakovSvetlin Nakov

    15+ years software engineering15+ years software engineering

    experienceexperience

    PhD in computer science fromPhD in computer science fromSofia UniversitySofia University

    Chairman of the Bulgarian AssociationChairman of the Bulgarian Association

    of Software Developers (BASD)of Software Developers (BASD)

    www.devbg.orgwww.devbg.org

    Author of 6 books about Java, .NETAuthor of 6 books about Java, .NET

    and software engineeringand software engineering

    Web site:Web site: www.nakov.comwww.nakov.com

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    3/120

    Table of ContentsTable of Contents

    Java 7Java 7 Introduction and ChronologyIntroduction and Chronology

    Dynamic Languages in JVMDynamic Languages in JVM

    Java ModularityJava Modularity Project JigsawProject Jigsaw

    Language Enhancements (Project Coin)Language Enhancements (Project Coin) Closures for JavaClosures for Java

    JSR 203: NIO 2JSR 203: NIO 2

    Other new features:Other new features: Compressed 64Compressed 64--bit oops, Garbagebit oops, Garbage--First GC,First GC,

    Upgraded ClassUpgraded Class--Loaders,Loaders, URLClassLoader.URLClassLoader.

    close()close(), Unicode 5.1,, Unicode 5.1, SCTP andSCTP and SDPSDP

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    4/120

    Introduction andIntroduction andChronologyChronology

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    5/120

    OpenJDKOpenJDK

    JDK7 is the second JDK done via theJDK7 is the second JDK done via the

    OpenJDK effortOpenJDK effort

    OpenJDK is free, openOpenJDK is free, open--source and GPLsource and GPL

    licensedlicensed

    A lot of the improvements of JDK7 areA lot of the improvements of JDK7 are

    separate projects on OpenJDKseparate projects on OpenJDK

    Some say that projects go under the cap ofSome say that projects go under the cap of

    OpenJDK to avoid the cumbersome and slowOpenJDK to avoid the cumbersome and slow

    JCP processJCP process

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    6/120

    Java 7Java 7 MilestonesMilestones

    Began in August 2006Began in August 2006 First supposed to be 7 milestonesFirst supposed to be 7 milestones

    Mark Reinhold extended them to 10Mark Reinhold extended them to 10

    Current status: M7 finished, presentationCurrent status: M7 finished, presentationmade with build89made with build89

    M10 expected to finish 09.09.2010M10 expected to finish 09.09.2010

    The last scheduled milestone cycle will beThe last scheduled milestone cycle will befollowed by a test and stabilization period offollowed by a test and stabilization period of

    indeterminate lengthindeterminate length, after which the final, after which the final

    release will be declaredrelease will be declared

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    7/120

    Theres No JSR YetTheres No JSR Yet

    A Java 7 JSR is supposed to be formed

    Java SE 6 was under the 'Umbrella' JSR 270

    JDK7 is in Eclipses low priority list because a

    lack of container JSR

    JDK7 cannot be finalized without a JSR

    There are some functionalities that also lacka JSR

    While doing this presentation we used the

    term JSR TBD in lieu of the missing JSR

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    8/120

    Source Control SystemSource Control System

    Official SCM is SVN, still

    Note: it takes a 'while' (e.g. one night)

    Unofficial Mercurial forest repositories

    available since November 2007

    Note: this also takes a 'while'

    >svn co https://jdk7.dev.java.net/svn/jdk7/trunk>svn co https://jdk7.dev.java.net/svn/jdk7/trunk

    >hg fclone http://hg.openjdk.java.net/>hg fclone http://hg.openjdk.java.net/

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    9/120

    Currently Supported IDEsCurrently Supported IDEs

    EclipseEclipse Both Eclipse 3.6M6 and E4 do not supportBoth Eclipse 3.6M6 and E4 do not support

    JDK7s syntaxJDK7s syntax

    or I couldnt figure it out or I couldnt figure it out Strangely enough the option is there:Strangely enough the option is there:

    Source compatibility: 1.7Source compatibility: 1.7

    NetBeansNetBeans 6.9 Beta supports JDK76.9 Beta supports JDK7

    Compiles successfully the M7 syntaxCompiles successfully the M7 syntax

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    10/120

    DynamicDynamicLanguages in JVMLanguages in JVM

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    11/120

    The Da Vinci Machine ProjectThe Da Vinci Machine Project

    Prototype a number of extensions to the JVMPrototype a number of extensions to the JVM A.k.a. Multi Language Virtual MachineA.k.a. Multi Language Virtual Machine

    http://openjdk.java.net/projects/mlvm/http://openjdk.java.net/projects/mlvm/

    Allows nonAllows non--Java dynamic languages to runJava dynamic languages to run

    efficiently in the JVMefficiently in the JVM

    Emphasis is on general purpose extensionsEmphasis is on general purpose extensions

    Hosted on OpenJDKHosted on OpenJDK

    Da Vinci: a multiDa Vinci: a multi--language renaissancelanguage renaissancefor the Java Virtual Machine architecturefor the Java Virtual Machine architecture

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    12/120

    Dynamic Languages in JVMDynamic Languages in JVM

    Da Vinci MachineDa Vinci Machine subsub--projects include:projects include: Dynamic invocationDynamic invocation

    ContinuationsContinuations

    TailTail--callscalls

    AndAnd interface injectioninterface injection

    JSR 292: Supporting Dynamically TypedJSR 292: Supporting Dynamically Typed

    Languages on the Java PlatformLanguages on the Java Platform

    The standard behindThe standard behind Da VinciDa Vinci MachineMachine

    Natural continuation of JSR 223: Scripting forNatural continuation of JSR 223: Scripting for

    the Java Platform implemented in JDK 6the Java Platform implemented in JDK 6

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    13/120

    Dynamic Languages in JVM (2)Dynamic Languages in JVM (2)

    New JVM instructionNew JVM instruction invokedynamicinvokedynamic

    Allows extremely fast dynamic methodAllows extremely fast dynamic method

    invocation through method handlesinvocation through method handles

    Will enable JRuby, Jython, Groovy and otherWill enable JRuby, Jython, Groovy and otherdynamic and scripting languages to calldynamic and scripting languages to call

    dynamic methods natively at bytecode leveldynamic methods natively at bytecode level

    Method handlesMethod handles

    Lightweight references to a methodLightweight references to a method

    java.dyn.MethodHandlejava.dyn.MethodHandle

    Anonymous classes in the JVMAnonymous classes in the JVM

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    14/120

    Dynamic Languages in JVM (3)Dynamic Languages in JVM (3)

    Autonomous methodsAutonomous methods

    Methods that can be dynamically attached toMethods that can be dynamically attached to

    an existing class at runtimean existing class at runtime

    Interface injectionInterface injection Acquiring base interfaces and methodAcquiring base interfaces and method

    implementations at runtimeimplementations at runtime

    Continuations and stack introspectionContinuations and stack introspection Suspend / resume thread's execution stackSuspend / resume thread's execution stack

    Tail calls and tail recursionTail calls and tail recursion

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    15/120

    Dynamic Languages in JVM (4)Dynamic Languages in JVM (4)

    Runtime support for closuresRuntime support for closures

    Closure is a lambdaClosure is a lambda--expression boundexpression bound

    (closed) to its environment(closed) to its environment

    MultimethodsMultimethods Dispatch a method overload depending on theDispatch a method overload depending on the

    actual arguments at runtimeactual arguments at runtime

    Faster reflection and faster interfaceFaster reflection and faster interfaceinvocation based on dynamic invocationinvocation based on dynamic invocation

    Symbolic freedom for identifier namesSymbolic freedom for identifier names

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    16/120

    Dynamic InvokeDynamic Invoke ExampleExample

    static void greeter(String x) {

    System.out.println("Hello, " + x);

    }

    static MethodHandle greeterMethodHandle =

    MethodHandles.lookup().findStatic(

    DynamicInvocation.class, "greeter", MethodType.

    methodType(void.class, String.class));

    static {

    Linkage.registerBootstrapMethod(

    "bootstrapDynamic");

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    17/120

    Dynamic InvokeDynamic Invoke Example (2)Example (2)

    private static CallSite bootstrapDynamic(Class caller, String name, MethodType type) {

    if (type.parameterCount() == 1 && name == "hail") {

    MethodHandle target = MethodHandles.

    convertArguments(greeterMethodHandle, type);

    CallSite site = new CallSite(caller, name, type);site.setTarget(target);

    System.out.println("Set the CallSite target to " +

    greeterMethodHandle);

    return site;

    }}

    public static void main(String... args) {

    InvokeDynamic.hail("dynamic invocation");

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    18/120

    Java ModularityJava ModularityProject JigsawProject Jigsaw

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    19/120

    ModularizationModularization IntroductionIntroduction

    TheThe JDK and theJDK and the JRE, have always beenJRE, have always beendelivered as massive, indivisible artifactsdelivered as massive, indivisible artifacts

    The growth of the platform has thusThe growth of the platform has thus

    inevitably led to the growth of the basicinevitably led to the growth of the basic JREJREdownloaddownload

    which now stands at well over 14MBwhich now stands at well over 14MB

    despite heroic engineering efforts such asdespite heroic engineering efforts such as

    thethe Pack200Pack200 class file compression formatclass file compression format

    Java KernelJava Kernel andand QuickstarterQuickstarter features dofeatures do

    improve download time and startup time, atimprove download time and startup time, at

    least for Windows usersleast for Windows users

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    20/120

    The Real SolutionThe Real Solution

    The most promising way to improve the keyThe most promising way to improve the keymetrics ofmetrics of

    Download timeDownload time

    Startup timeStartup time

    And memory footprintAnd memory footprint

    Is to attack the root problem headIs to attack the root problem head--on:on:

    Divide the JDK into a set of well specified andDivide the JDK into a set of well specified andseparate, yet interdependent, modulesseparate, yet interdependent, modules

    A side effect is that JAR format has toA side effect is that JAR format has to

    reworkedreworked

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    21/120

    Alan Bateman: Its DifficultAlan Bateman: Its Difficult

    Suppose you are using the Logging APISuppose you are using the Logging API Logging requires NIO (for file locking)Logging requires NIO (for file locking)

    And JMX (as loggers are managed)And JMX (as loggers are managed)

    JMX requires JavaBeans, JNDI, RMI andJMX requires JavaBeans, JNDI, RMI andCORBA (JMX remote API mandates that theCORBA (JMX remote API mandates that the

    RMI connector support both JRMP and IIOP)RMI connector support both JRMP and IIOP)

    JNDI requiresJNDI requires java.applet.Appletjava.applet.Applet (huh?) and(huh?) and

    JavaBeans has dependencies on AWT, SwingJavaBeans has dependencies on AWT, Swing

    Not satisfied with this, JavaBeans hasNot satisfied with this, JavaBeans has

    persistent delegates that create dependenciespersistent delegates that create dependencies

    on JDBC and moreon JDBC and more

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    22/120

    How to Do It?How to Do It?

    Modularizing the JDK requires a moduleModularizing the JDK requires a modulesystem capable of supporting such an effortsystem capable of supporting such an effort

    It requires, in particular, a module systemIt requires, in particular, a module system

    whose core can be implemented directlywhose core can be implemented directlywithin the Java virtual machinewithin the Java virtual machine

    Modularizing is best done with a moduleModularizing is best done with a module

    system thats tightly integrated with the Javasystem thats tightly integrated with the Java

    languagelanguage

    Otherwise the compileOtherwise the compile--time moduletime module

    environment can differ dramatically from theenvironment can differ dramatically from the

    runrun--time module environmenttime module environment

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    23/120

    Which Module System?Which Module System?

    JSR 277 proposes the JAM module systemJSR 277 proposes the JAM module system

    Some of its rich, nonSome of its rich, non--declarative featuresdeclarative features

    would be impossible to implement its corewould be impossible to implement its core

    functionality directly within the JVMfunctionality directly within the JVM

    Therefore Sun halted the developmentTherefore Sun halted the development

    JSR 294 is chartered to extend the languageJSR 294 is chartered to extend the language

    and JVM to support modular programmingand JVM to support modular programming

    Well receivedWell received for its simplicity and its utility tofor its simplicity and its utility to

    existing module systems such as OSGiexisting module systems such as OSGi

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    24/120

    Which Module System? (2)Which Module System? (2)

    OSGiOSGi

    May 2007May 2007:: OSGi 4.1 standardized as JSROSGi 4.1 standardized as JSR--291291

    Reasonably mature, stable, and robustReasonably mature, stable, and robust

    Implemented within Apache Harmony JVMImplemented within Apache Harmony JVM

    Not at all integrated with the Java languageNot at all integrated with the Java language

    Jigsaw created to modularize JDK7Jigsaw created to modularize JDK7 Will not be an official part of the Java SEWill not be an official part of the Java SE 77

    Platform Specification and might not bePlatform Specification and might not be

    supported by other SEsupported by other SE 7 implementations7 implementations

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    25/120

    Status and ExamplesStatus and Examples

    Probably JSR 294 will be chosenProbably JSR 294 will be chosen

    There are issues, JSR 294 is inactive (paused)There are issues, JSR 294 is inactive (paused)

    Not implemented yet (b89),Not implemented yet (b89), java.lang.modulejava.lang.module

    Example (may, and probably will, change)Example (may, and probably will, change)

    module [email protected] [email protected], [email protected] {

    requires [email protected], [email protected];

    permits M6; // only M6 can depend on M1

    }

    module M;

    package P;

    public class Foo {...}

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    26/120

    JSR 308:JSR 308:(Extended) Annotations(Extended) Annotations

    on Java Typeson Java Types

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    27/120

    JSR 308JSR 308 IntroductionIntroduction

    JavaJava SESE 6 permits annotations only on6 permits annotations only ondeclarationsdeclarations

    JSR 308 extends Javas annotation systemJSR 308 extends Javas annotation system

    so that annotations may appear on nearlyso that annotations may appear on nearlyany use of a typeany use of a type

    JSR 308 is backwardJSR 308 is backward--compatible andcompatible and

    continues to permit those annotationscontinues to permit those annotations

    Two new types of annotations (target wise):Two new types of annotations (target wise):

    ElementType.TYPE_USEElementType.TYPE_USE

    ElementType.TYPE_PARAMETERElementType.TYPE_PARAMETER

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    28/120

    JSR 308: ExamplesJSR 308: Examples

    public static void main() {//for generic type arguments in a generic method

    JSR308Example2.method("...");

    //for type parameters and type parameter bounds:

    Collection c = null;

    //for class inheritance:class UnmodifiableListimplements

    @Readonly List { }

    }

    //for throws clauses:

    void monitorTemperature() throws @Critical Exception {}

    //for method receivers:

    public String toString() @Readonly { return null; }

    // helper only

    public static T method(String s) {return null;}

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    29/120

    Small LanguageSmall LanguageEnhancementsEnhancements(Project Coin)(Project Coin)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    30/120

    ProjectProject CoinCoin IntroductionIntroduction

    Project Coin unites all language changes toProject Coin unites all language changes tothe Java Lang Specification (JLS) to bethe Java Lang Specification (JLS) to be

    added to JDK 7added to JDK 7

    Open call for proposalsOpen call for proposals From February 27, 2009From February 27, 2009

    Through March 30, 2009Through March 30, 2009

    70 proposal forms70 proposal forms

    9 were chosen9 were chosen

    No Milestone selected yet (so not all featuresNo Milestone selected yet (so not all features

    are available)are available)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    31/120

    The Chosen OnesThe Chosen Ones

    Strings in SwitchStrings in Switch

    By Joseph D. DarcyBy Joseph D. Darcy

    Automatic Resource ManagementAutomatic Resource Management

    By Joshua BlochBy Joshua Bloch

    Improved Type Inference for GenericImproved Type Inference for Generic

    Instance CreationInstance Creation

    By Jeremy MansonBy Jeremy Manson

    Simplified Varargs Method InvocationSimplified Varargs Method Invocation

    By Bob LeeBy Bob Lee

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    32/120

    The Chosen Ones (2)The Chosen Ones (2)

    Collection LiteralsCollection Literals By Joshua BlochBy Joshua Bloch

    Indexing access syntax for Lists and MapsIndexing access syntax for Lists and Maps

    By Shams MahmoodBy Shams Mahmood

    Language support for JSR 292Language support for JSR 292

    By John RoseBy John Rose

    Binary LiteralsBinary Literals

    Underscores in numbersUnderscores in numbers

    By Derek FosterBy Derek Foster

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    33/120

    1. Strings in Switch1. Strings in Switch

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    34/120

    Strings in SwitchStrings in Switch

    Syntactic sugarSyntactic sugar

    // Finally! - strings in switch

    String s = "";

    switch (s) {

    case "Edno":out.println("1");

    break;

    case "Dve":

    out.println("2");

    break;default:

    out.println("Unknown BG number.");

    break;

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    35/120

    2. Automatic Resource2. Automatic ResourceManagement (ARM)Management (ARM)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    36/120

    ARMARM The ProblemThe Problem

    AA resourceresource is as an object that must beis as an object that must beclosed manuallyclosed manually

    InputStreamInputStream,, ReaderReader,, WriterWriter,, DB connectionDB connection

    Manual resource termination has proven uglyManual resource termination has proven uglyand error proneand error prone

    Even good programmers get it wrongEven good programmers get it wrong

    Resource leaks or even outright failures,Resource leaks or even outright failures,which may be silentwhich may be silent

    If an exception is thrown in the try block, and inIf an exception is thrown in the try block, and in

    the finally block, the second supplants the firstthe finally block, the second supplants the first

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    37/120

    ARMARM The Problem (2)The Problem (2)

    Wheres the problem with this code?Wheres the problem with this code?

    If an exception is thrown in the try block, and inIf an exception is thrown in the try block, and inthe finally block, the second supplants the firstthe finally block, the second supplants the first

    Was "Text" written successfully?Was "Text" written successfully?

    BufferedWriter br =

    new BufferedWriter(new FileWriter(path));

    try {

    br.write("Text");

    } finally {

    br.close();

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    38/120

    How Its Done (One Resource)How Its Done (One Resource)

    BufferedWriter br =

    new BufferedWriter(new FileWriter(path));

    try {// This exception is more important

    br.write("Text");

    } finally {

    try {

    // ... than this one

    br.close();

    } catch(IOException ioe) {}

    }

    TryTry--finallyfinally with one resource:with one resource:

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    39/120

    How Its Done (Two Resources)How Its Done (Two Resources)

    static void copy(String src, String dest) throws IOException {

    InputStream in = new FileInputStream(src);

    try {

    OutputStream out = new FileOutputStream(dest);

    try {

    byte[] buf = new byte[8 * 1024];

    int n;

    while ((n = in.read(buf)) >= 0)

    out.write(buf, 0, n);

    } finally {

    try {

    out.close();

    } catch(IOException ioe) {}

    }} finally {

    try {

    in.close();

    } catch(IOException ioe) {}}

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    40/120

    Code isCode is now 4now 4 lineslines

    Removed the boring nestedRemoved the boring nested trytry,, catchcatch,,finallyfinally,, close()close() clausesclauses

    The first exception is thrown if a problemThe first exception is thrown if a problem

    occurs, theoccurs, the close()close() exception is hiddenexception is hidden

    ARM SyntaxARM Syntax Two ResourcesTwo Resources

    static void copy(String src, String dest) throws IOException {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);}

    }

    A t ti RA t ti R

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    41/120

    Automatic ResourceAutomatic ResourceManagementManagement

    ARM statementARM statement is a form of the try statementis a form of the try statementthat declares one or more resourcesthat declares one or more resources

    The scope of these resource declarations isThe scope of these resource declarations is

    limited to the statementlimited to the statement

    When the statement completes, whetherWhen the statement completes, whether

    normally or abruptly, all of its resources arenormally or abruptly, all of its resources are

    closed automaticallyclosed automatically

    As of b89 ARM is not yet available, butAs of b89 ARM is not yet available, but

    definitely going to be inside JDK7definitely going to be inside JDK7

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    42/120

    An Interface Must be ChosenAn Interface Must be Chosen

    A class must implement a designatedA class must implement a designatedinterface to make it eligible for automaticinterface to make it eligible for automatic

    resource managementresource management

    An obvious choice would beAn obvious choice would be CloseableCloseable

    close()close() method throwsmethod throws IOExceptionIOException

    What about general purpose resources?What about general purpose resources?

    package java.io;

    import java.io.IOException;

    public interface Closeable {

    public void close() throws IOException;

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    43/120

    An Interface Must be Chosen (2)An Interface Must be Chosen (2)

    It is possible to retrofitIt is possible to retrofit CloseableCloseable with awith aparameterized superinterfaceparameterized superinterface

    Disposable would become:Disposable would become:

    package java.lang;

    public interface Disposable {

    void close() throws X;}

    package java.io;

    import java.io.IOException;

    public interface Closeable extends Disposable {

    void close() throws IOException;

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    44/120

    ARMARM NotesNotes

    No interface is chosen, nor implemented yetNo interface is chosen, nor implemented yet

    As of b89As of b89

    MigrationMigration

    Any resource that must be closed manuallyAny resource that must be closed manually

    should be retrofitted to implement theshould be retrofitted to implement the

    DisposableDisposable interfaceinterface

    In the JDK, this includes:In the JDK, this includes:

    CloseableCloseable (all streams implement it)(all streams implement it)

    ConnectionConnection,, StatementStatement, and, and ResultSetResultSet

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    45/120

    Suppressed ExceptionsSuppressed Exceptions

    ARM discards suppressed exceptionsARM discards suppressed exceptions

    Proposal implies they can be saved byProposal implies they can be saved by

    adding them in suppressing exception viaadding them in suppressing exception via

    two new methods totwo new methods to ThrowableThrowable:: void addSuppressedException(Throwable)void addSuppressedException(Throwable)

    Throwable[]getSuppressedExceptions()Throwable[]getSuppressedExceptions()

    As of b89 not implemented and its not clearAs of b89 not implemented and its not clear

    whether they will bewhether they will be

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    46/120

    3. Improved Type3. Improved TypeInference for GenericInference for Generic

    Instance CreationInstance Creation

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    47/120

    What is the Fuss All About?What is the Fuss All About?

    Simply this:Simply this:

    becomes: becomes:

    is called the diamondis called the diamond

    Cannot be omitted because no difference canCannot be omitted because no difference can

    be made between rawbe made between raw HashMapHashMap and aand aparameterized oneparameterized one

    [Ctrl+Shift+F][Ctrl+Shift+F] failsfails onon diamond in NetBeans 6.9diamond in NetBeans 6.9

    Implemented in b89Implemented in b89

    Map anagrams =

    new HashMap();

    Map anagrams = new HashMap();

    Diamond : AdvancedDiamond : Advanced

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    48/120

    Diamond : AdvancedDiamond : AdvancedExampleExample

    This is supposed to work:This is supposed to work:

    but does not yet (as of b89)but does not yet (as of b89)

    public class AdvancedExample {

    public static void main() {

    method("", new ArrayList(), new ArrayList());}

    public static T method(

    T a, List b, List c) {

    return a;

    }}

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    49/120

    4. Simplified4. SimplifiedVarargs MethodVarargs Method

    InvocationInvocation

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    50/120

    Simplified Varargs MethodSimplified Varargs Method

    The compiler currently generates an "unsafeThe compiler currently generates an "unsafeoperation" warningoperation" warning

    When a programmer tries to invoke a varargsWhen a programmer tries to invoke a varargs

    method with amethod with a nonnon--reifiablereifiable varargs typevarargs type

    JDK 7 will move the warning from the callJDK 7 will move the warning from the call

    site to the method declarationsite to the method declaration

    Major advantagesMajor advantages

    Reduces the total number of warningsReduces the total number of warnings

    reported to and suppressed by programmersreported to and suppressed by programmers

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    51/120

    A Picture is Worth a 1000 WordsA Picture is Worth a 1000 Words

    /** NOT WORKING in b89, no change with jdk1.6.0_20 */

    public static void main() {

    Callable t = null;

    //OLD: Warning: "uses unchecked or unsafe operationsList merged = asList(t);

    System.out.println(merged);

    }

    // NEW: Warning: "unchecked generic array creation"

    private static List asList(T... elements ) {

    return Arrays.asList(elements);

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    52/120

    Simplified VarargsSimplified Varargs ExampleExample

    interface Sink {

    void add(T... a);

    }

    /** NOT WORKING in b89, no change with jdk1.6.0_20 */

    interface BrokenSinkextends Sink {

    // OLD: no warning

    // NEW: Warning: "Overriddes non-reifiable varargs typewith array"

    void add(T[] a);

    }

    /** NOT WORKING in b89, no change with jdk1.6.0_20 */

    class StringSink implements Sink {// OLD: no warning

    // NEW: Warning: "override generates a more specific

    varargs type erasure"

    public void add(String... a) {}

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    53/120

    5. Collection5. CollectionLiteralsLiterals

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    54/120

    Collection LiteralsCollection Literals

    Again a syntax sugarAgain a syntax sugar

    Not yet available, so no demoNot yet available, so no demo

    /** NOT WORKING in b89 */

    public static void main(String... args) {

    List list = ["One", "Two"];

    Set set = {"One", "Two", "Three"};

    Map map = {"One" : 1, "Two" : 2};

    // Note:

    Object s = { }; // empty set;

    Object m = {:}; // empty map;}

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    55/120

    6. Indexing Access6. Indexing Access

    Syntax for ListsSyntax for Listsand Mapsand Maps

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    56/120

    Collection IndexersCollection Indexers

    Syntax sugarSyntax sugar/** NOT WORKING in b89 */

    public static void main(String... args) {

    List list =

    Arrays.asList(new String[]{"a", "b", "c"});Map map =

    new HashMap(4);

    // THE OLD WAY

    String firstElement = list.get(0);

    map.put(1, "One");// THE NEW WAY (NOT IMPLEMENTED YET)

    String firstElement = list[0];

    map[1] = "One";

    }

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    57/120

    7. Language Support7. Language Supportfor JSR 292for JSR 292

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    58/120

    JSR 292 Support inJSR 292 Support in javacjavac

    java.dyn.InvokeDynamicjava.dyn.InvokeDynamic will accept anywill accept anymethod call and turn it into anmethod call and turn it into aninvokedynamicinvokedynamic instructioninstruction

    The typeThe type java.dyn.MethodHandlejava.dyn.MethodHandle will acceptwill accept

    any argument and return typesany argument and return types

    Bytecode names acceptable to the JVM can beBytecode names acceptable to the JVM can be

    spelled from Java code, using #" "spelled from Java code, using #" "

    java.dyn.InvokeDynamicjava.dyn.InvokeDynamic serves as a bareserves as a barereference type: anything implicitly converts to itreference type: anything implicitly converts to it

    It can be cast to anything, but it is not aIt can be cast to anything, but it is not asubtype ofsubtype ofjava.lang.Objectjava.lang.Object

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    59/120

    JSR 292JSR 292 ExampleExample

    // Works in b89

    // type (Object, int) -> boolean

    boolean z =

    java.dyn.InvokeDynamic.myEquals(x, y);

    // Works in b89MethodHandle hndl = MethodHandles.lookup().findVirtual(

    PrintStream.class, "println", MethodType.methodType(

    void.class, String.class));

    hndl.invokeGeneric(System.out, "Merhaba");

    // Works in b89

    String #"g 1 $!$#%" = "Text";

    System.out.println(#"g 1 $!$#%");

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    60/120

    9. Underscores in9. Underscores inNumbersNumbers

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    61/120

    Underscores in NumbersUnderscores in Numbers

    /** WORKING in b89 */

    public static void main(String... args) {

    // THE OLD WAY

    int oldBillion = 1000000000;

    // THE NEW WAY

    int newBillion = 1_000_000_000;

    out.println(oldBillion);

    out.println(newBillion);

    }

    Too much sugar can cause diabetesToo much sugar can cause diabetes

    May seem useless,May seem useless, butbut dontdont judgejudge tootoo quicklyquickly

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    62/120

    10.10. Binary LiteralsBinary Literals

    Bi i lBi i l

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    63/120

    Binary LiteralsBinary Literals

    /** WORKING in b89 */

    public static void main(String... args) {

    // THE OLD WAY

    int oldBinary1 = 153;

    int oldBinary2 = 128 ^ 0 ^ 0 ^ 16 ^ 8 ^ 0 ^ 0 ^ 1;

    // THE NEW WAY

    int newBinary = 0b1001_1001;out.println(oldBinary1);

    out.println(oldBinary2);

    out.println(format("[0b1001_1001] is {0}", newBinary));

    }

    The syntax is 0b11110000;The syntax is 0b11110000;

    See where underscores come in handy?See where underscores come in handy?

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    64/120

    Closures in JavaClosures in JavaFirstFirst--class Functions, Functionclass Functions, Function

    Types and Lambda ExpressionsTypes and Lambda Expressions

    Wh t Cl ?Wh t Cl ?

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    65/120

    What are Closures?What are Closures?

    ClosuresClosures definitiondefinition Closures are functions that are evaluated inClosures are functions that are evaluated in

    an environment containing one or morean environment containing one or more

    bound variables [Wikipedia]bound variables [Wikipedia]

    In English: a little snippet of code (function)In English: a little snippet of code (function)

    that can be passed as argument of somethat can be passed as argument of some

    method for subsequent executionmethod for subsequent execution

    Closures come from functional programmingClosures come from functional programminglanguages like Lisplanguages like Lisp

    Limited support for closures since JDK 1.1,Limited support for closures since JDK 1.1,

    in the form of anonymous classesin the form of anonymous classes

    FirstFirst--class and Anonymousclass and Anonymous

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    66/120

    FirstFirst class and Anonymousclass and AnonymousFunctionsFunctions

    FirstFirst--classclass functions are programmingare programmingparadigm that supportsparadigm that supports

    Data structure holding a function with itsData structure holding a function with its

    parameters and return typeparameters and return type

    Passing functions as arguments to otherPassing functions as arguments to other

    functions and invoking themfunctions and invoking them

    Returning functions as resultReturning functions as result

    Anonymous functionsAnonymous functions

    Functions without name (lambda functions)Functions without name (lambda functions)

    Take some parameters and return a valueTake some parameters and return a value

    L bd E iL bd E i

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    67/120

    Lambda ExpressionsLambda Expressions

    Lambda calculusLambda calculus A formal mathematical system for functionA formal mathematical system for function

    definition, function application and recursiondefinition, function application and recursion

    Typed and untyped lambda calculusTyped and untyped lambda calculus

    Lambda expressionsLambda expressions

    Anonymous functions that take parametersAnonymous functions that take parameters

    and return values, e.g.and return values, e.g.

    x x*xx x*x

    (x, y) x*x + y*y(x, y) x*x + y*y

    A.k.a.A.k.a. lambda functionslambda functions

    P j t L bdP j t L bd

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    68/120

    Project LambdaProject Lambda

    Project LambdaProject Lambda GoalsGoals

    To formulate a proposal to add firstTo formulate a proposal to add first--classclass

    functions, function types, and lambdafunctions, function types, and lambda

    expressions (informally, "closures") to Javaexpressions (informally, "closures") to Java

    To implement a prototype suitable for inclusionTo implement a prototype suitable for inclusion

    in JDKin JDK 77

    Official Web SiteOfficial Web Site http://openjdk.java.net/projects/lambda/http://openjdk.java.net/projects/lambda/

    StatusStatus

    StrawStraw--man proposal, still no JSRman proposal, still no JSR

    L bd E i i JL bd E i i J

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    69/120

    Lambda Expressions in JavaLambda Expressions in Java

    Lambda expressions in Java use the # syntaxLambda expressions in Java use the # syntax Function with no arguments, returns 42:Function with no arguments, returns 42:

    Function withFunction with intint argument:argument:

    Function with twoFunction with two intint arguments:arguments:

    #()(42)#()(42)

    #(int x)(x + x)#(int x)(x + x)

    #(int x, int y)(x * y)#(int x, int y)(x * y)

    Lambda Expressions withLambda Expressions with

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    70/120

    Lambda Expressions withLambda Expressions withCode BlockCode Block

    Lambda expressions can have bodyLambda expressions can have body A Java code block:A Java code block:

    #(int x, int y) {#(int x, int y) {

    int z = (int)Math.sqrt(x*x + y*y);int z = (int)Math.sqrt(x*x + y*y);if (z < 10)if (z < 10)

    return x;return x;

    else if (z > 10)else if (z > 10)

    return y;return y;

    elseelsereturn 0;return 0;

    }}

    F ti TF ti T

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    71/120

    Function TypesFunction Types

    Function types are data types that hold aFunction types are data types that hold areference to lambda function or method:reference to lambda function or method:

    Functions stored in variable of function typeFunctions stored in variable of function type

    can be invoked like any other function:can be invoked like any other function:

    #int() fortyTwo = #()(42);#int() fortyTwo = #()(42);

    #int(int) triple = #(int x)(3*x); #int(int,int)#int(int) triple = #(int x)(3*x); #int(int,int)

    mult = #(int x, int y)(x * y);mult = #(int x, int y)(x * y);

    System.out.println(fortyTwo());System.out.println(fortyTwo());

    int result = triple(5);int result = triple(5);

    int multResult = mult(3, 5);int multResult = mult(3, 5);

    F nctions as Arg mentsF nctions as Arg ments

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    72/120

    Functions as ArgumentsFunctions as Arguments

    Lambda functions can be passed asLambda functions can be passed asarguments to a methodarguments to a method

    public long sum(int[] arr, #int(int) fn) {public long sum(int[] arr, #int(int) fn) {

    long sum = 0;long sum = 0;

    for (int element : arr)for (int element : arr)

    sum += fn(element);sum += fn(element);

    return sum;return sum;

    }}

    int[] arr = new int[] {1, 2, 3, 4};int[] arr = new int[] {1, 2, 3, 4};

    long squaresSum = sum(arr, #(int x)(x*x));long squaresSum = sum(arr, #(int x)(x*x));

    System.out.println(squaresSum); // 30System.out.println(squaresSum); // 30

    Functions as Return ValueFunctions as Return Value

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    73/120

    Functions as Return ValueFunctions as Return Value

    Lambda functions can be returned as resultLambda functions can be returned as resultof method execution:of method execution:

    public #int(int) adder(int c) {public #int(int) adder(int c) {

    return #(int x)(x + c);return #(int x)(x + c);

    }}

    #int(int) a42 = adder(42);#int(int) a42 = adder(42);

    System.out.println(a42(2)); // 44System.out.println(a42(2)); // 44

    Function ConversionsFunction Conversions

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    74/120

    Function ConversionsFunction Conversions

    Lambda functions can be converted to abstractLambda functions can be converted to abstractclass / interface defining a single method:class / interface defining a single method:

    Thread th = new Thread(new Runnable() {Thread th = new Thread(new Runnable() {

    public void run() {public void run() {

    doSomeStuff();doSomeStuff();

    doMoreStuff();doMoreStuff();

    }}

    });});

    Thread th = new Thread(#(){Thread th = new Thread(#(){

    doSomeStuff(); doMoreStuff(); } )doSomeStuff(); doMoreStuff(); } )

    Variable CaptureVariable Capture

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    75/120

    Variable CaptureVariable Capture

    We can share local state between the body ofWe can share local state between the body ofa lambda expression and its enclosing scopea lambda expression and its enclosing scope

    A new keywordA new keyword sharedsharedis introducedis introduced

    shared int comparisonsCount = 0;shared int comparisonsCount = 0;Collections.sort(data, #(String a, String b) {Collections.sort(data, #(String a, String b) {

    comparisonsCount++;comparisonsCount++;

    return a.compareTo(b);return a.compareTo(b);

    });});

    System.out.println(comparisonsCount);System.out.println(comparisonsCount);

    Instance CaptureInstance Capture

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    76/120

    Instance CaptureInstance Capture

    TheThe thisthis reference of the enclosing classreference of the enclosing classcould be accessed in a lambda expression:could be accessed in a lambda expression:

    class CountingSorter {class CountingSorter {

    private int comparisonsCount = 0;private int comparisonsCount = 0;

    Collections.sort(data,Collections.sort(data,

    #(String a, String b) {#(String a, String b) {

    comparisonsCount++;comparisonsCount++;

    return a.compareTo(b);return a.compareTo(b);}}

    ););

    Extension MethodsExtension Methods

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    77/120

    Extension MethodsExtension Methods

    Extension methodsExtension methods allow the author of anallow the author of anexisting interface to add methods to thatexisting interface to add methods to that

    interface while preserving compatibilityinterface while preserving compatibility

    For example, we need to add a method forFor example, we need to add a method for

    filtering members from any collection byfiltering members from any collection by

    given Boolean condition:given Boolean condition:

    Set set =Set set =

    new Set(new int[] {1,2,3,4,5});new Set(new int[] {1,2,3,4,5});

    Set filteredSet =Set filteredSet =

    set.filter(#boolean(int x)(x < 3));set.filter(#boolean(int x)(x < 3));

    Extension Methods (2)Extension Methods (2)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    78/120

    Extension Methods (2)Extension Methods (2)

    Defining extension methods:Defining extension methods:class Collections {class Collections {static Set filter(static Set filter(Set s, #boolean(T) pred) { }Set s, #boolean(T) pred) { }

    static Set map(static Set map(Set s, #S(T) func) { }Set s, #S(T) func) { }

    }}

    interface Set extends Collection {interface Set extends Collection {

    Set filter(#boolean(T)) import staticSet filter(#boolean(T)) import staticCollections.filter;Collections.filter;

    map(#S(T)) import static Collections.map; map(#S(T)) import static Collections.map;}}

    Extension Methods (3)Extension Methods (3)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    79/120

    Extension Methods (3)Extension Methods (3)

    Using extension methods:Using extension methods:int ints = new int[] { 1, 2, 3, 4, 5 };int ints = new int[] { 1, 2, 3, 4, 5 };int[] transformedInts =int[] transformedInts =s.filter(#(int x)(x % 2 == 0))s.filter(#(int x)(x % 2 == 0)).map(#(int x)(x + 3));.map(#(int x)(x + 3));

    // transformedInts = { 5, 7 }// transformedInts = { 5, 7 }

    int[] transformedInts =int[] transformedInts =

    Collections.map(Collections.map(Collections.filter(s, #(int x)(x % 2 == 0)),Collections.filter(s, #(int x)(x % 2 == 0)),#(int x)(x + 3)#(int x)(x + 3)

    ););

    Parallel Arrays APIParallel Arrays API

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    80/120

    Parallel Arrays APIParallel Arrays API

    ParallelArrayParallelArrayis ideal candidate foris ideal candidate forextension methodsextension methods

    Can utilize efficiently multiCan utilize efficiently multi--core /core /

    multiprocessor systemsmultiprocessor systems

    The classThe class ParallelArrayParallelArrayallows parallelallows parallel

    aggregate operations over a collectionaggregate operations over a collection

    Apply transformation to each elementApply transformation to each element

    Map each element to a new elementMap each element to a new element

    Select subset of the elements by predicateSelect subset of the elements by predicate

    Reduce elements to a single value (e.g. sum)Reduce elements to a single value (e.g. sum)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    81/120

    JSR 203:JSR 203:

    More New I/O APIs for theMore New I/O APIs for theJava Platform (NIO.2)Java Platform (NIO.2)

    NIO2NIO2 IntroductionIntroduction

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    82/120

    NIO2NIO2 IntroductionIntroduction

    New I/ONew I/O oror nonnon--blocking I/O, usuallyblocking I/O, usuallycalledcalled NIONIO

    Collection ofCollection of JavaJava APIsAPIs that offer features forthat offer features for

    intensiveintensive I/OI/O operationsoperations

    It was introduced with the J2SEIt was introduced with the J2SE 1.41.4

    NIO was developed under theNIO was developed under the JavaJava

    Community ProcessCommunity Process as JSR 51as JSR 51

    As of 2006, an extension to NIO, called NIO2,As of 2006, an extension to NIO, called NIO2,

    is being developed under JSR 203is being developed under JSR 203

    JSR 203 is scheduled to be included inJSR 203 is scheduled to be included in JDK 7JDK 7

    Cool New Things: resolve()Cool New Things: resolve()

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    83/120

    Cool New Things: resolve()Cool New Things: resolve()

    resolve()resolve() resolves a relative pathresolves a relative path

    public static void resolve() {

    FileSystem fileSystem = FileSystems.getDefault();

    Path currentDir = fileSystem.getPath(".");

    Path srcDir = fileSystem.getPath("src");

    Path file1 = fileSystem.getPath("./Test.java");

    Path file2 = fileSystem.getPath(../Copy.java");

    System.out.println(

    "file2: " +

    currentDir.resolve(srcDir).resolve(file2));

    }

    Cool New Things: relativize()Cool New Things: relativize()

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    84/120

    Cool New Things: relativize()Cool New Things: relativize()

    relativize()relativize() makes path relativemakes path relative

    public static void relativize() {

    FileSystem fileSystem = FileSystems.getDefault();

    Path source = fileSystem.getPath(".");

    Path temp = fileSystem.getPath("/temp");

    Path relativeSource =

    source.toAbsolutePath().

    relativize(temp.toAbsolutePath());

    System.out.println(relativeSource);

    }

    How to Copy a FileHow to Copy a File

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    85/120

    How to Copy a FileHow to Copy a File

    Up to Java 6 (w/o channels) it looks like this:Up to Java 6 (w/o channels) it looks like this:

    Familiar?Familiar?

    Most developers write this incorrectlyMost developers write this incorrectly

    try {

    from = new FileInputStream(fromFile);

    to = new FileOutputStream(toFile);

    byte[] buffer = new byte[4096];

    int bytesRead;

    while ((bytesRead = from.read(buffer)) != -1)

    to.write(buffer, 0, bytesRead); // write

    } finally {

    // Close the streams "to" and "from"

    }

    How to Copy a File (2)How to Copy a File (2)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    86/120

    How to Copy a File (2)How to Copy a File (2)

    java.io.Filejava.io.File is used to represent a fileis used to represent a file

    @since 1.0@since 1.0

    Is there a way to copy metadata?Is there a way to copy metadata?

    JDK7:JDK7: java.io.Filejava.io.File -->> java.nio.file.Pathjava.nio.file.Path

    java.io.Filejava.io.File wont be deprecated, but shouldwont be deprecated, but should

    Path is a better name (might be a dir, right?)Path is a better name (might be a dir, right?)

    // java.io.File -> java.nio.filePath

    Path p = new File("/foo/bar.txt").toPath();

    FileSystem local = FileSystems.getDefault();

    Path from = local.getPath(FileName);

    Path to = local.getPath(toFileName);

    from.copyTo(to);

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    87/120

    Upgrade ClassUpgrade Class--Loader ArchitectureLoader Architecture

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    88/120

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    89/120

    Compressed 64Compressed 64--bitbitObject PointersObject Pointers

    What is an oop?What is an oop?

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    90/120

    What is an oop?What is an oop?

    An "oop", or "ordinary object pointer" in theAn "oop", or "ordinary object pointer" in theJVM is a managed object pointerJVM is a managed object pointer

    It is normally the same size as a nativeIt is normally the same size as a native

    machine pointermachine pointer

    64 bits on an 6464 bits on an 64--bit OSbit OS

    32 bits on an 3232 bits on an 32--bit OSbit OS

    3232--bit JVM can address less than 4GBbit JVM can address less than 4GB 6464--bit JVM can address all the available RAMbit JVM can address all the available RAM

    But this costs a lot of memory lost in oopsBut this costs a lot of memory lost in oops

    Compressed oopsCompressed oops

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    91/120

    Compressed oopsCompressed oops

    Compressed oops allow to address up to 32GB RAM with 32-bit pointers

    The address space is mapped using a 64-bit

    base and 32-bit oop This allows applications to address up to four

    billion objects (not bytes)

    Java heap can grow up to 32 GB

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    92/120

    GarbageGarbage--First GCFirst GC(G1)(G1)

    GarbageGarbage--First GC (G1)First GC (G1)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    93/120

    GarbageGarbage First GC (G1)First GC (G1)

    G1 (garbageG1 (garbage--first) garbage collectorfirst) garbage collector Improved performance and less freeze timeImproved performance and less freeze time

    ServerServer--style garbage collectorstyle garbage collector

    Targeted for multiTargeted for multi--processors with largeprocessors with largememoriesmemories

    Meets a soft realMeets a soft real--time goal with hightime goal with high

    probabilityprobability

    Added in Milestone1 (02.01.2009)Added in Milestone1 (02.01.2009)

    Released in Java 6 update 6u14Released in Java 6 update 6u14

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    94/120

    Method to close aMethod to close aURLClassLoaderURLClassLoader

    URLClassLoader.closeURLClassLoader.close()()

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    95/120

    URLClassLoader.closeURLClassLoader.close()()

    URLClassLoaderURLClassLoader has new method calledhas new method calledclose()close()

    since b48 of JDK 7since b48 of JDK 7

    Closes anyCloses any JARJAR files that were open by thefiles that were open by the

    loaderloader

    Allows the application to delete/replace theseAllows the application to delete/replace thesefiles and if necessary to create new loadersfiles and if necessary to create new loaders

    Invalidates the loader, so that no new classesInvalidates the loader, so that no new classes

    can be loaded from itcan be loaded from it

    /** @since 1.7 */ urlClassLoader.close();

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    96/120

    Unicode 5.1Unicode 5.1

    Unicode 5.1 in Java 7Unicode 5.1 in Java 7

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    97/120

    Unicode 5.1 in Java 7Unicode 5.1 in Java 7

    Java 6 is Unicode 4.0 compliantJava 6 is Unicode 4.0 compliant Java 7 will be Unicode 5.1 compliantJava 7 will be Unicode 5.1 compliant

    Most upMost up--toto--date version of Unicode is 5.2date version of Unicode is 5.2

    (October 2009)(October 2009) What's new in Unicode 5 ?What's new in Unicode 5 ?

    Unicode 5.0 will include 1,369 new charactersUnicode 5.0 will include 1,369 new characters

    and 9 new blocks (~alphabets)and 9 new blocks (~alphabets) Unicode 5.1 will haveUnicode 5.1 will have 1,6241,624 additional charadditional charss

    making a grand total ofmaking a grand total of 100,713100,713 breaking thebreaking the

    100K mark for the first time100K mark for the first time

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    98/120

    SCTPSCTP

    (Stream Control(Stream ControlTransmission Protocol)Transmission Protocol)

    SCTPSCTP

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    99/120

    SCSC

    Stream Control Transmission ProtocolStream Control Transmission Protocol(SCTP) is a(SCTP) is a Transport LayerTransport Layer protocolprotocol

    serving in a similar role as TCP andserving in a similar role as TCP and UDPUDP

    Features of SCTP include:Features of SCTP include: MultihomingMultihoming support: both endpoints of asupport: both endpoints of a

    connection can consist of more than one IPconnection can consist of more than one IP

    Chunks delivered within independent streamsChunks delivered within independent streams

    Protect against flooding attacksProtect against flooding attacks

    No Windows supports SCTPNo Windows supports SCTP

    JDK7: The SCTP ProjectJDK7: The SCTP Project

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    100/120

    jj

    The goal of this Project is:The goal of this Project is: To develop an API for the Stream ControlTo develop an API for the Stream Control

    Transport Protocol (SCTP)Transport Protocol (SCTP)

    And a corresponding OpenJDK prototypeAnd a corresponding OpenJDK prototype

    The API is implementation agnosticThe API is implementation agnostic

    Included in build 56Included in build 56

    Could be hacked to work with JDK6Could be hacked to work with JDK6

    Currently only Solaris is supportedCurrently only Solaris is supported

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    101/120

    SDPSDP(Sockets Direct Protocol)(Sockets Direct Protocol)

    SDPSDP

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    102/120

    TheThe Sockets Direct ProtocolSockets Direct Protocol (SDP) is a(SDP) is anetworking protocol originally defined bynetworking protocol originally defined by

    thethe InfiniBand Trade AssociationInfiniBand Trade Association

    Transport agnostic protocol for Remote DirectTransport agnostic protocol for Remote Direct

    Memory AccessMemory Access (RDMA)(RDMA)

    RDMA is aRDMA is a direct memory accessdirect memory access from onefrom one

    computers memory into anothers withoutcomputers memory into anothers without

    involving either one'sinvolving either one's operating systemoperating system

    JDK7s SDP implementation works,JDK7s SDP implementation works,

    unfortunately, only on Solarisunfortunately, only on Solaris

    Java 7 New FeaturesJava 7 New Features

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    103/120

    QuestionsQuestions??

    Java 7 New FeaturesJava 7 New Features

    ResourcesResources Java ChronologyJava Chronology

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    104/120

    gygy

    JDK 7JDK 7 FeaturesFeatures http://openjdk.java.net/projects/jdk7/featuhttp://openjdk.java.net/projects/jdk7/featu

    res/res/

    JDK 7JDK 7 MilestonesMilestones

    http://openjdk.java.net/projects/jdk7/mileshttp://openjdk.java.net/projects/jdk7/milestones/tones/

    ResourcesResources Dynamic LangsDynamic Langs

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    105/120

    y gy g

    New JDK 7 Feature: Support for DynamicallyNew JDK 7 Feature: Support for DynamicallyTyped Languages in the Java Virtual MachineTyped Languages in the Java Virtual Machine

    http://java.sun.com/developer/technicalArtihttp://java.sun.com/developer/technicalArticles/DynTypeLang/cles/DynTypeLang/

    John Rose's weblog at Sun MicrosystemsJohn Rose's weblog at Sun Microsystems

    http://blogs.sun.com/jrose/http://blogs.sun.com/jrose/

    JSR 292: Supporting Dynamically TypedJSR 292: Supporting Dynamically Typed

    Languages on the Java PlatformLanguages on the Java Platform http://jcp.org/en/jsr/detail?id=292http://jcp.org/en/jsr/detail?id=292

    ResourcesResources Project JigsawProject Jigsaw

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    106/120

    j gj g

    Project Jigsaw: Language changes for ModulesProject Jigsaw: Language changes for Modules http://openjdk.java.net/projects/jigsaw/dochttp://openjdk.java.net/projects/jigsaw/doc/language.html/language.html

    Project JigsawProject Jigsaw Mark Reinholds BlogMark Reinholds Blog

    http://blogs.sun.com/mr/entry/jigsawhttp://blogs.sun.com/mr/entry/jigsaw

    Is the JDK Losing its Edge(s)?Is the JDK Losing its Edge(s)?

    http://blogs.sun.com/alanb/entry/http://blogs.sun.com/alanb/entry/

    is_the_jdk_losing_itsis_the_jdk_losing_its

    ResourcesResources JSR 308JSR 308

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    107/120

    Type Annotations Specification (JSR 308)Type Annotations Specification (JSR 308) http://types.cs.washington.edu/jsr308/specihttp://types.cs.washington.edu/jsr308/specification/javafication/java--annotationannotation--design.htmldesign.html

    Type Annotations FAQ (JSR 308)Type Annotations FAQ (JSR 308)

    http://types.cs.washington.edu/jsr308/jshttp://types.cs.washington.edu/jsr308/js

    r308r308--faq.htmlfaq.html

    The Checker Framework: Custom PluggableThe Checker Framework: Custom Pluggable

    Types for JavaTypes for Java

    http://types.cs.washington.edu/checkerhttp://types.cs.washington.edu/checker--framework/current/checkersframework/current/checkers--manual.htmlmanual.html

    ResourcesResources Project CoinProject Coin

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    108/120

    jj

    Project CoinProject Coin http://wikis.sun.com/display/ProjectCoin/20http://wikis.sun.com/display/ProjectCoin/20

    09ProposalsTOC09ProposalsTOC

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--February/000001.htmlFebruary/000001.html

    Strings in switchStrings in switch

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin--

    dev/2009dev/2009--February/000001.htmlFebruary/000001.html Automatic Resource ManagementAutomatic Resource Management

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin--

    dev/2009dev/2009--February/000011.htmlFebruary/000011.html

    ResourcesResources Project Coin (2)Project Coin (2)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    109/120

    Improved Type Inference for GenericImproved Type Inference for GenericInstance CreationInstance Creation

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin--dev/2009dev/2009--February/000009.htmlFebruary/000009.html

    Simplified Varargs Method InvocationSimplified Varargs Method Invocation

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--March/000316.htmlMarch/000316.html

    Collection LiteralsCollection Literals http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--March/001193.htmlMarch/001193.html

    ResourcesResources Project Coin (3)Project Coin (3)

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    110/120

    Indexing access syntax for Lists and MapsIndexing access syntax for Lists and Maps

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--March/001108.htmlMarch/001108.html

    Language support for JSR 292Language support for JSR 292

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin--dev/2009dev/2009--March/001077.htmlMarch/001077.html

    Binary LiteralsBinary Literals

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--April/001627.htmlApril/001627.html

    Underscores in numbersUnderscores in numbers

    http://mail.openjdk.java.net/pipermail/coinhttp://mail.openjdk.java.net/pipermail/coin

    --dev/2009dev/2009--March/001208.htmlMarch/001208.html

    ResourcesResources ClosuresClosures

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    111/120

    Project LambdaProject Lambda http://openjdk.java.net/projects/lambda/http://openjdk.java.net/projects/lambda/

    Project Lambda: StrawProject Lambda: Straw--Man ProposalMan Proposal

    http://cr.openjdk.java.net/~mr/lambda/strawhttp://cr.openjdk.java.net/~mr/lambda/straw--man/man/ Closures for JavaClosures for Java Mark Reinholds BlogMark Reinholds Blog

    http://blogs.sun.com/mr/entry/closureshttp://blogs.sun.com/mr/entry/closures

    ResourcesResources NIO2NIO2

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    112/120

    Java New I/OJava New I/O http://en.wikipedia.org/wiki/New_I/Ohttp://en.wikipedia.org/wiki/New_I/O

    JSR 203: The Open RoadJSR 203: The Open Road java.nio.filejava.nio.file

    http://today.java.net/pub/a/today/2008/07/0http://today.java.net/pub/a/today/2008/07/03/jsr3/jsr--203203--newnew--filefile--apis.htmlapis.html

    ResourcesResources Compressed oopsCompressed oops

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    113/120

    Compressed oops in the Hotspot JVMCompressed oops in the Hotspot JVM http://wikis.sun.com/display/HotSpotInternahttp://wikis.sun.com/display/HotSpotInternals/CompressedOopsls/CompressedOops

    WikipediaWikipedia 6464--bitbit

    http://en.wikipedia.org/wiki/64http://en.wikipedia.org/wiki/64--bitbit

    ILP32, LP64, and LLP64ILP32, LP64, and LLP64

    http://wiki.wireshark.org/Development/Win64http://wiki.wireshark.org/Development/Win64

    C Programming LanguageC Programming Language

    http://en.wikipedia.org/wiki/C_(programminghttp://en.wikipedia.org/wiki/C_(programming

    _language)_language)

    ResourcesResources Garbage CollectionGarbage Collection

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    114/120

    GarbageGarbage--First Garbage CollectionFirst Garbage Collection

    http://research.sun.com/jtech/pubs/04http://research.sun.com/jtech/pubs/04--g1g1--

    paperpaper--ismm.pdfismm.pdf

    JavaOne: G1 Garbage CollectorJavaOne: G1 Garbage Collector

    http://tech.puredanger.com/2008/05/09/javaonehttp://tech.puredanger.com/2008/05/09/javaone--g1g1--garbagegarbage--collectorcollector

    Garbage CollectionGarbage Collection WikipediaWikipedia

    http://en.wikipedia.org/wiki/Garbage_collectiohttp://en.wikipedia.org/wiki/Garbage_collectio

    n_(computer_science)n_(computer_science)

    WikipediaWikipedia Hard and Soft RealHard and Soft Real--time Systemstime Systems

    http://en.wikipedia.org/wiki/Realhttp://en.wikipedia.org/wiki/Real--

    time_computing#Hard_and_soft_realtime_computing#Hard_and_soft_real--time_systemstime_systems

    ResourcesResources UpgradeUpgradeClassLoader ArchitectureClassLoader Architecture

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    115/120

    ClassLoader ArchitectureClassLoader Architecture

    Draft Proposal for ClassLoader Deadlock FixDraft Proposal for ClassLoader Deadlock Fix http://www.mailhttp://www.mail--archive.com/corearchive.com/[email protected]/[email protected]/msg00863.html

    java.lang.ClassLoader.loadClassInternal(Stjava.lang.ClassLoader.loadClassInternal(St

    ring)ring) is Too Restrictiveis Too Restrictive

    http://bugs.sun.com/bugdatabase/view_bug.dohttp://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4670071?bug_id=4670071

    ResourcesResources URL ClassLoaderURL ClassLoader

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    116/120

    Closing aClosing a URLClassLoaderURLClassLoader http://blogs.sun.com/michaelmcm/entry/closihttp://blogs.sun.com/michaelmcm/entry/closing_a_urlclassloaderng_a_urlclassloader

    ClassClass URLClassLoaderURLClassLoader close()close()

    http://download.java.net/jdk7/docs/api/javahttp://download.java.net/jdk7/docs/api/java/net/URLClassLoader.html#close()/net/URLClassLoader.html#close()

    ResourcesResources Unicode 5.1Unicode 5.1

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    117/120

    JDK 7JDK 7 FeaturesFeatures Unicode 5.1Unicode 5.1 http://openjdk.java.net/projects/jdk7/featuhttp://openjdk.java.net/projects/jdk7/features/#f497res/#f497

    What's new in Unicode 5.0?What's new in Unicode 5.0?

    http://babelstone.blogspot.com/2005/11/whathttp://babelstone.blogspot.com/2005/11/what

    ss--newnew--inin--unicodeunicode--50.html50.html

    What's new in Unicode 5.1?What's new in Unicode 5.1?

    http://babelstone.blogspot.com/2007/06/whathttp://babelstone.blogspot.com/2007/06/whatss--newnew--inin--unicodeunicode--51.html51.html

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    118/120

    ResourcesResources SDPSDP

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    119/120

    Understanding the Sockets Direct ProtocolUnderstanding the Sockets Direct Protocol http://java.sun.com/docs/books/tutorial/sdphttp://java.sun.com/docs/books/tutorial/sdp/sockets/index.html/sockets/index.html

    Sockets Direct ProtocolSockets Direct Protocol WikipediaWikipedia

    http://en.wikipedia.org/wiki/Sockets_Directhttp://en.wikipedia.org/wiki/Sockets_Direct_Protocol_Protocol

    Remote Direct Memory AccessRemote Direct Memory Access

    http://en.wikipedia.org/wiki/Remote_Direct_http://en.wikipedia.org/wiki/Remote_Direct_Memory_AccessMemory_Access

    ZeroZero--copycopy

    http://en.wikipedia.org/wiki/Zerohttp://en.wikipedia.org/wiki/Zero--copycopy

    ResourcesResources AuthorsAuthors

  • 8/8/2019 Java 7 New Features Nakov EGJUG Cairo 2 May 2010

    120/120

    Authors of this presentation:Authors of this presentation: Svetlin NakovSvetlin Nakov

    http://www.nakov.com/blog/http://www.nakov.com/blog/

    Mihail StoynovMihail Stoynov

    http://mihail.stoynov.com/blog/http://mihail.stoynov.com/blog/