SlideShare a Scribd company logo
1 of 75
Download to read offline
Java SE 7
JUG SummerCamp 2011
  La Rochelle, France
Java 7 JUG Summer Camp
Fork / Join

         Project Coin



                     NIO.2
              invokedynamic
                        (...)
Fork / Join
java.lang.Thread
     java.lang.Runnable

     wait()
<5   notify()
     synchronized
Thread thread = new Thread() {
   public void run() {
     System.out.println(">>> Hello!");
   }
};

thread.start();
thread.join();
java.util.concurrent

       executors
       concurrent queues
       concurrent collections
       atomic variables
5, 6   synchronization patterns
       rich locks
class Sum implements Callable<Long> {

    private final long from;
    private final long to;

    Sum(long from, long to) {
      this.from = from;
      this.to = to;
    }

    public Long call() {
      long acc = 0;
      for (long i = from; i <= to; i++) {
        acc = acc + i;
      }
      return acc;
    }
}
ExecutorService executor = Executors.newFixedThreadPool(2);

List<Future<Long>> results = executor.invokeAll(asList(
    new Sum(0, 10),
    new Sum(100, 1000),
    new Sum(10000, 1000000)
));

for (Future<Long> result : results) {
    System.out.println(result.get());
}
1.0   Threads made easy
1.1
1.2
1.3
1.4


 5    Concurrency made easier
 6



 7    Parallelism made easier
Sum of an array


n1   n2   n3   n4 n5   n6 n7     n8   n9     ...    ...     ...   ...


     sum1                 sum2               sum3
            sum1 + sum2                                   sum3 + (...)
                                 total sum
How many occurrences of
“java.util.List” in this filesystem tree?
Load into RAM (1 thread)

              Folder
                                         Document
 subfolders: List<Folder>
                             lines: List<String>
 documents: List<Document>




     Divide & conquer (#cores threads)
ForkJoinPool    Your work

Thread management      Split
Maximize parallelism   Fork subtasks
      Work stealing    Join subtasks
                       Compose results
ForkJoinTask




       join()                   join()
                                              RecursiveAction
                fork()    fork()
                                                     vs
                                               RecursiveTask

Child ForkJoinTask       Child ForkJoinTask
16


                          Folder word
                         counting task


 10
                                                         5
                                1


Document word      Document word              Folder word
 counting task      counting task            counting task



                                3                                 2

          fork()
                            Document word        Document word
  n       join()             counting task        counting task
(F/J demo)
Speedup&
7"

6"

5"

4"

3"

2"

1"
     2"   4"    6"   8"   10"   12"
                                      #cores
No I/O
No synchronization / locks

Decompose in simple recursive tasks
Do not decompose below a threshold

Take advantage of multicores with no pain

You have more F/J candidate algorithms than
you think!
try-with-resources
private void writeSomeData() throws IOException {
  DataOutputStream out = new DataOutputStream(new FileOutputStream("data"));
  out.writeInt(666);
  out.writeUTF("Hello");
  out.close();
}
private void writeSomeData() throws IOException {
  DataOutputStream out = new DataOutputStream(new FileOutputStream("data"));
  out.writeInt(666);
  out.writeUTF("Hello");
  out.close();
}


                                        what if...
private void writeSomeData() throws IOException {
  DataOutputStream out = null;
  try {
    out = new DataOutputStream(new FileOutputStream("data"));
    out.writeInt(666);
    out.writeUTF("Hello");
  } finally {
    if (out != null) {
      out.close();
    }
  }
}
private void writeSomeData() throws IOException {
  DataOutputStream out = null;
  try {
    out = new DataOutputStream(new FileOutputStream("data"));
    out.writeInt(666);
    out.writeUTF("Hello");
  } finally {
    if (out != null) {
      out.close();
    }
  }
}
                         ...this is still far from correct!
try (

    FileOutputStream out = new FileOutputStream("output");
    FileInputStream in1 = new FileInputStream(“input1”);
    FileInputStream in2 = new FileInputStream(“input2”)

) {

    // Do something useful with those 3 streams!
    // out, in1 and in2 will be closed in any case

    out.write(in1.read());
    out.write(in2.read());
}
public class AutoClose implements AutoCloseable {

    @Override
    public void close() {
      System.out.println(">>> close()");
      throw new RuntimeException("Exception in close()");
    }

    public void work() throws MyException {
      System.out.println(">>> work()");
      throw new MyException("Exception in work()");
    }
}
AutoClose autoClose = new AutoClose();
try {
  autoClose.work();
} finally {
  autoClose.close();
}
AutoClose autoClose = new AutoClose();
try {
  autoClose.work();
} finally {
  autoClose.close();
}



>>> work()
   >>> close()
   java.lang.RuntimeException: Exception in close()
          at AutoClose.close(AutoClose.java:6)
          at AutoClose.runWithMasking(AutoClose.java:19)
          at AutoClose.main(AutoClose.java:52)
AutoClose autoClose = new AutoClose();
try {
  autoClose.work();
} finally {
  autoClose.close();
}


            MyException
                        m   asked by Run
>>> work()                              time  Exception
   >>> close()
   java.lang.RuntimeException: Exception in close()
          at AutoClose.close(AutoClose.java:6)
          at AutoClose.runWithMasking(AutoClose.java:19)
          at AutoClose.main(AutoClose.java:52)
“Caused by” ≠ “Also happened”
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
  autoClose.work();
} catch (MyException e) {
  myException = e;
  throw e;
} finally {
  if (myException != null) {
    try {
      autoClose.close();
    } catch (Throwable t) {
      myException.addSuppressed(t);
    }
  } else {
    autoClose.close();
  }
}
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
  autoClose.work();
} catch (MyException e) {
  myException = e;
  throw e;
} finally {
  if (myException != null) {
    try {
      autoClose.close();
    } catch (Throwable t) {
      myException.addSuppressed(t);
    }
  } else {
    autoClose.close();
  }
}
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
  autoClose.work();
} catch (MyException e) {
  myException = e;
  throw e;
} finally {
  if (myException != null) {
    try {
      autoClose.close();
    } catch (Throwable t) {
      myException.addSuppressed(t);
    }
  } else {
    autoClose.close();
  }
}
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
  autoClose.work();
} catch (MyException e) {
  myException = e;
  throw e;
} finally {
  if (myException != null) {
    try {
      autoClose.close();
    } catch (Throwable t) {
      myException.addSuppressed(t);
    }
  } else {
    autoClose.close();
  }
}
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
  autoClose.work();
} catch (MyException e) {
  myException = e;
  throw e;
} finally {
  if (myException != null) {
    try {
      autoClose.close();
    } catch (Throwable t) {
      myException.addSuppressed(t);
    }
  } else {
    autoClose.close();
  }
}
try (AutoClose autoClose = new AutoClose()) {
  autoClose.work();
}
try (AutoClose autoClose = new AutoClose()) {
        autoClose.work();
      }



>>> work()
   >>> close()
   MyException: Exception in work()
          at AutoClose.work(AutoClose.java:11)
          at AutoClose.main(AutoClose.java:16)
          Suppressed: java.lang.RuntimeException: Exception in close()
                 at AutoClose.close(AutoClose.java:6)
                 at AutoClose.main(AutoClose.java:17)
public void compress(String input, String output)
             throws IOException {
  try(
    FileInputStream fin = new FileInputStream(input);
    FileOutputStream fout = new FileOutputStream(output);
    GZIPOutputStream out = new GZIPOutputStream(fout)
  ) {
    byte[] buffer = new byte[4096];
    int nread = 0;
    while ((nread = fin.read(buffer)) != -1) {
       out.write(buffer, 0, nread);
    }
  }
}
public void compress(String input, String output) throws IOException {   public void compress(String paramString1, String paramString2)
  try(                                                                              throws IOException {
    FileInputStream fin = new FileInputStream(input);                           FileInputStream localFileInputStream = new FileInputStream(paramString1);
    FileOutputStream fout = new FileOutputStream(output);                    Object localObject1 = null;
    GZIPOutputStream out = new GZIPOutputStream(fout)                           try {
  ) {                                                                               FileOutputStream localFileOutputStream = new FileOutputStream(paramString2);
    byte[] buffer = new byte[4096];                                              Object localObject2 = null;
    int nread = 0;                                                                  try {
    while ((nread = fin.read(buffer)) != -1) {                                          GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localFileOutputStream);
       out.write(buffer, 0, nread);                                                  Object localObject3 = null;
    }                                                                                   try {
  }                                                                                         byte[] arrayOfByte = new byte[4096];
}                                                                                           int i = 0;
                                                                                            while ((i = localFileInputStream.read(arrayOfByte)) != -1) {
                                                                                                localGZIPOutputStream.write(arrayOfByte, 0, i);
                                                                                            }
                                                                                        } catch (Throwable localThrowable6) {
                                                                                            localObject3 = localThrowable6;
                                                                                            throw localThrowable6;
                                                                                        } finally {
                                                                                            if (localGZIPOutputStream != null) {
                                                                                                if (localObject3 != null) {
                                                                                                    try {
                                                                                                        localGZIPOutputStream.close();
                                                                                                    } catch (Throwable localThrowable7) {
                                                                                                        localObject3.addSuppressed(localThrowable7);
                                                                                                    }
                                                                                                } else {
                                                                                                    localGZIPOutputStream.close();
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    } catch (Throwable localThrowable4) {
                                                                                        localObject2 = localThrowable4;
                                                                                        throw localThrowable4;
                                                                                    } finally {
                                                                                        if (localFileOutputStream != null) {
                                                                                            if (localObject2 != null) {
                                                                                                try {
                                                                                                    localFileOutputStream.close();
                                                                                                } catch (Throwable localThrowable8) {
                                                                                                    localObject2.addSuppressed(localThrowable8);
                                                                                                }
                                                                                            } else {
                                                                                                localFileOutputStream.close();
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                } catch (Throwable localThrowable2) {
                                                                                    localObject1 = localThrowable2;
                                                                                    throw localThrowable2;
                                                                                } finally {
                                                                                    if (localFileInputStream != null) {
                                                                                        if (localObject1 != null) {
                                                                                            try {
                                                                                                localFileInputStream.close();
                                                                                            } catch (Throwable localThrowable9) {
                                                                                                localObject1.addSuppressed(localThrowable9);
                                                                                            }
                                                                                        } else {
                                                                                            localFileInputStream.close();
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
Not just syntactic sugar
Clutter-free, correct code

close():
   - be more specific than java.lang.Exception
   - no exception if it can’t fail
   - no exception that shall not be suppressed
       (e.g., java.lang.InterruptedException)
Diamond <>
List<String> strings = new LinkedList<Integer>();




Map<String, List<String>> contacts =
            new HashMap<Integer, String>();
List<String> strings = new LinkedList<String>();
strings.add("hello");
strings.add("world");

Map<String, List<String>> contacts = new HashMap<String, List<String>>();
contacts.put("Julien", new LinkedList<String>());
contacts.get("Julien").addAll(asList("Foo", "Bar", "Baz"));
List<String> strings = new LinkedList<>();
strings.add("hello");
strings.add("world");

Map<String, List<String>> contacts = new HashMap<>();
contacts.put("Julien", new LinkedList<String>());
contacts.get("Julien").addAll(asList("Foo", "Bar", "Baz"));
Map<String, String> map = new HashMap<String, String>() {
   {
     put("foo", "bar");
     put("bar", "baz");
   }
};
Map<String, String> map = new HashMap<>() {
   {
     put("foo", "bar");
     put("bar", "baz");
   }
};
Map<String, String> map = new HashMap<>() {
   {
     put("foo", "bar");
     put("bar", "baz");
   }
};


Diamond.java:43: error: cannot infer type arguments for HashMap;
        Map<String, String> map = new HashMap<>() {
                                              ^
  reason: cannot use '<>' with anonymous inner classes
1 error
class SomeClass<T extends Serializable & CharSequence> { }




                                     Non-denotable type
class SomeClass<T extends Serializable & CharSequence> { }




                                        Non-denotable type

SomeClass<?> foo = new SomeClass<String>();
SomeClass<?> fooInner = new SomeClass<String>() { };

SomeClass<?> bar = new SomeClass<>();

SomeClass<?> bar = new SomeClass<>() { };
class SomeClass<T extends Serializable & CharSequence> { }




                                        Non-denotable type

SomeClass<?> foo = new SomeClass<String>();
SomeClass<?> fooInner = new SomeClass<String>() { };

SomeClass<?> bar = new SomeClass<>();

SomeClass<?> bar = new SomeClass<>() { };




                                  No denotable type
                                  to generate a class
Less ceremony when using generics

No diamond with inner classes
Simplified varargs
private static <T> void doSomethingBad(List<T> list, T... values) {
    values[0] = list.get(0);
}

public static void main(String[] args) {
    List list = Arrays.asList("foo", "bar", "baz");
    doSomethingBad(list, 1, 2, 3);
}
This yields warnings + crash:
private static <T> void doSomethingBad(List<T> list, T... values) {
    values[0] = list.get(0);
}

public static void main(String[] args) {
    List list = Arrays.asList("foo", "bar", "baz");
    doSomethingBad(list, 1, 2, 3);
}
                           Heap Pollution: List = List<String>
private static <T> void doSomethingGood(List<T> list, T... values) {
    for (T value : values) {
        list.add(value);
    }
}
private static <T> void doSomethingGood(List<T> list, T... values) {
    for (T value : values) {
        list.add(value);
    }
}


$ javac Good.java
Note: Good.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
@SuppressWarnings({“unchecked”,“varargs”})
public static void main(String[] args) {
    List<String> list = new LinkedList<>();
    doSomethingGood(list, "hi", "there", "!");
}




$ javac Good.java
$
static, final methods, constructors



@SafeVarargs
private static <T> void doSomethingGood(List<T> list, T... values) {
    for (T value : values) {
        list.add(value);
    }
}
Mark your code as safe for varargs

You can’t cheat with @SafeVarags

Remove @SuppressWarnings in client code
and pay attention to real warnings
Multi-catch & more
 precise rethrow
Class<?> stringClass = Class.forName("java.lang.String");
Object instance = stringClass.newInstance();
Method toStringMethod = stringClass.getMethod("toString");
System.out.println(toStringMethod.invoke(instance));
try {
    Class<?> stringClass = Class.forName("java.lang.String");
    Object instance = stringClass.newInstance();
    Method toStringMethod = stringClass.getMethod("toString");
    System.out.println(toStringMethod.invoke(instance));
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}
try {
    Class<?> stringClass = Class.forName("java.lang.String");
    Object instance = stringClass.newInstance();
    Method toStringMethod = stringClass.getMethod("toString");
    System.out.println(toStringMethod.invoke(instance));
} catch (Throwable t) {
    t.printStackTrace();
}
try {
    Class<?> stringClass = Class.forName("java.lang.String");
    Object instance = stringClass.newInstance();
    Method toStringMethod = stringClass.getMethod("toString");
    System.out.println(toStringMethod.invoke(instance));
} catch (Throwable t) {
    t.printStackTrace();
}




                           How about SecurityException?
try {
    Class<?> stringClass = Class.forName("java.lang.String");
    Object instance = stringClass.newInstance();
    Method toStringMethod = stringClass.getMethod("toString");
    System.out.println(toStringMethod.invoke(instance));
} catch (ClassNotFoundException | InstantiationException |
         IllegalAccessException | NoSuchMethodException |
         InvocationTargetException e) {
    e.printStackTrace();
}




                           Union of alternatives
catch (SomeException e)




Now implicitly final unless assigned...
static class SomeRootException extends Exception { }
static class SomeChildException extends SomeRootException { }
static class SomeOtherChildException extends SomeRootException { }

public static void main(String... args) throws Throwable {
try {
    throw new SomeChildException();
} catch (SomeRootException firstException) {
    try {
        throw firstException;
    } catch (SomeOtherChildException secondException) {
        System.out.println("I got you!");
    }
}
static class SomeRootException extends Exception { }
static class SomeChildException extends SomeRootException { }
static class SomeOtherChildException extends SomeRootException { }

public static void main(String... args) throws Throwable {
try {
    throw new SomeChildException();
} catch (SomeRootException firstException) {
    try {
        throw firstException;
    } catch (SomeOtherChildException secondException) {
        System.out.println("I got you!");
    }
}


$ javac Imprecise.java
Imprecise.java:13: error: exception SomeOtherChildException is never thrown in body of
corresponding try statement
            } catch (SomeOtherChildException secondException) {
              ^
1 error
Less clutter
Be precise
Do not capture unintended exceptions

Better exception flow analysis
Minor additions
// 123 in decimal, octal, hexadecimal and binary
byte decimal = 123;
byte octal = 0_173;
byte hexadecimal = 0x7b;
byte binary = 0b0111_1011;

// Other values
double doubleValue = 1.111_222_444F;
long longValue = 1_234_567_898L;
long longHexa = 0x1234_3b3b_0123_cdefL;
public static boolean isTrue(String str) {
    switch(str.trim().toUpperCase()) {
        case "OK":
        case "YES":
        case "TRUE":
            return true;

        case "KO":
        case "NO":
        case "FALSE":
            return false;

        default:
            throw new IllegalArgumentException("Not a valid true/false string.");
    }
}
public static boolean isTrue(String s) {
    String str = s.trim().toUpperCase();
    int jump = -1;
    switch(str.hashCode()) {
        case 2404:
            if (str.equals("KO")) {
                 jump = 3;                        Bucket
            }
            break;
(...)
    switch(jump) {
(...)
        case 3:
        case 4:
        case 5:
            return false;
        default:                                           Real code
            throw new IllegalArgumentException(
        "Not a valid true/false string.");
    }
}
Oracle Technology Network (more soon...)


           Fork and Join: Java Can Excel at
         Painless Parallel Programming Too!
                            http://goo.gl/tostz



           Better Resource Management with
          Java SE 7: Beyond Syntactic Sugar
                           http://goo.gl/7ybgr
Julien Ponge
                 @jponge

  http://gplus.to/jponge

http://julien.ponge.info/

julien.ponge@insa-lyon.fr

More Related Content

What's hot

3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Uehara Junji
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyIván López Martín
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4Eugeniy Tyumentcev
 
The Ring programming language version 1.5.2 book - Part 25 of 181
The Ring programming language version 1.5.2 book - Part 25 of 181The Ring programming language version 1.5.2 book - Part 25 of 181
The Ring programming language version 1.5.2 book - Part 25 of 181Mahmoud Samir Fayed
 

What's hot (18)

Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with Groovy
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Kotlin meets Gadsu
Kotlin meets GadsuKotlin meets Gadsu
Kotlin meets Gadsu
 
разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4разработка серверов и серверных приложений лекция №4
разработка серверов и серверных приложений лекция №4
 
The Ring programming language version 1.5.2 book - Part 25 of 181
The Ring programming language version 1.5.2 book - Part 25 of 181The Ring programming language version 1.5.2 book - Part 25 of 181
The Ring programming language version 1.5.2 book - Part 25 of 181
 

Viewers also liked

Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
AlpesJUG - Communautés opensource, stratégies et écueils
AlpesJUG - Communautés opensource, stratégies et écueilsAlpesJUG - Communautés opensource, stratégies et écueils
AlpesJUG - Communautés opensource, stratégies et écueilsjulien.ponge
 
IzPack at Devoxx 2010
IzPack at Devoxx 2010IzPack at Devoxx 2010
IzPack at Devoxx 2010julien.ponge
 
NHM Data Portal: first steps toward the Graph-of-Life
NHM Data Portal: first steps toward the Graph-of-LifeNHM Data Portal: first steps toward the Graph-of-Life
NHM Data Portal: first steps toward the Graph-of-LifeEdward Baker
 
Towards automated monitoring of Orthoptera (and some other noisy stuff)
Towards automated monitoring of Orthoptera (and some other noisy stuff)Towards automated monitoring of Orthoptera (and some other noisy stuff)
Towards automated monitoring of Orthoptera (and some other noisy stuff)Edward Baker
 
The Great Pretenders 4
The Great Pretenders 4The Great Pretenders 4
The Great Pretenders 4Edward Baker
 
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...Edward Baker
 
Cockroaches: from the beginning
Cockroaches: from the beginningCockroaches: from the beginning
Cockroaches: from the beginningEdward Baker
 
Nature Live! Cockroaches from the beginning (31/07/2011)
Nature Live! Cockroaches from the beginning (31/07/2011)Nature Live! Cockroaches from the beginning (31/07/2011)
Nature Live! Cockroaches from the beginning (31/07/2011)Edward Baker
 
Scratchpads & Citizen Science
Scratchpads & Citizen ScienceScratchpads & Citizen Science
Scratchpads & Citizen ScienceEdward Baker
 
Biodiversity Informatics at the Natural History Museum
Biodiversity Informatics at the Natural History MuseumBiodiversity Informatics at the Natural History Museum
Biodiversity Informatics at the Natural History MuseumEdward Baker
 
Chương 4 Lý thuyết hành vi của người sản xuất
Chương 4 Lý thuyết hành vi của người sản xuấtChương 4 Lý thuyết hành vi của người sản xuất
Chương 4 Lý thuyết hành vi của người sản xuấtNguyễn Ngọc Phan Văn
 

Viewers also liked (12)

Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
AlpesJUG - Communautés opensource, stratégies et écueils
AlpesJUG - Communautés opensource, stratégies et écueilsAlpesJUG - Communautés opensource, stratégies et écueils
AlpesJUG - Communautés opensource, stratégies et écueils
 
IzPack at Devoxx 2010
IzPack at Devoxx 2010IzPack at Devoxx 2010
IzPack at Devoxx 2010
 
NHM Data Portal: first steps toward the Graph-of-Life
NHM Data Portal: first steps toward the Graph-of-LifeNHM Data Portal: first steps toward the Graph-of-Life
NHM Data Portal: first steps toward the Graph-of-Life
 
Towards automated monitoring of Orthoptera (and some other noisy stuff)
Towards automated monitoring of Orthoptera (and some other noisy stuff)Towards automated monitoring of Orthoptera (and some other noisy stuff)
Towards automated monitoring of Orthoptera (and some other noisy stuff)
 
The Great Pretenders 4
The Great Pretenders 4The Great Pretenders 4
The Great Pretenders 4
 
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...
Biodiversity Informatics of the Cyperaceae: Where we stand and where we’re he...
 
Cockroaches: from the beginning
Cockroaches: from the beginningCockroaches: from the beginning
Cockroaches: from the beginning
 
Nature Live! Cockroaches from the beginning (31/07/2011)
Nature Live! Cockroaches from the beginning (31/07/2011)Nature Live! Cockroaches from the beginning (31/07/2011)
Nature Live! Cockroaches from the beginning (31/07/2011)
 
Scratchpads & Citizen Science
Scratchpads & Citizen ScienceScratchpads & Citizen Science
Scratchpads & Citizen Science
 
Biodiversity Informatics at the Natural History Museum
Biodiversity Informatics at the Natural History MuseumBiodiversity Informatics at the Natural History Museum
Biodiversity Informatics at the Natural History Museum
 
Chương 4 Lý thuyết hành vi của người sản xuất
Chương 4 Lý thuyết hành vi của người sản xuấtChương 4 Lý thuyết hành vi của người sản xuất
Chương 4 Lý thuyết hành vi của người sản xuất
 

Similar to Java 7 JUG Summer Camp

What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理maruyama097
 
Closures for Java
Closures for JavaClosures for Java
Closures for Javanextlib
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180Mahmoud Samir Fayed
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Python-GTK
Python-GTKPython-GTK
Python-GTKYuren Ju
 

Similar to Java 7 JUG Summer Camp (20)

What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
Closures for Java
Closures for JavaClosures for Java
Closures for Java
 
Java 7
Java 7Java 7
Java 7
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Inheritance
InheritanceInheritance
Inheritance
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 

More from julien.ponge

IzPack at LyonJUG'11
IzPack at LyonJUG'11IzPack at LyonJUG'11
IzPack at LyonJUG'11julien.ponge
 
IzPack - PoitouJUG
IzPack - PoitouJUGIzPack - PoitouJUG
IzPack - PoitouJUGjulien.ponge
 
IzPack - fOSSa 2009
IzPack - fOSSa 2009IzPack - fOSSa 2009
IzPack - fOSSa 2009julien.ponge
 
Slides Aquarium Paris 2008
Slides Aquarium Paris 2008Slides Aquarium Paris 2008
Slides Aquarium Paris 2008julien.ponge
 
IzPack Glassfish Lightning Talks 2008
IzPack Glassfish Lightning Talks 2008IzPack Glassfish Lightning Talks 2008
IzPack Glassfish Lightning Talks 2008julien.ponge
 

More from julien.ponge (7)

IzPack at LyonJUG'11
IzPack at LyonJUG'11IzPack at LyonJUG'11
IzPack at LyonJUG'11
 
FOSS - PoitouJUG
FOSS - PoitouJUGFOSS - PoitouJUG
FOSS - PoitouJUG
 
IzPack - PoitouJUG
IzPack - PoitouJUGIzPack - PoitouJUG
IzPack - PoitouJUG
 
IzPack - fOSSa 2009
IzPack - fOSSa 2009IzPack - fOSSa 2009
IzPack - fOSSa 2009
 
Slides Aquarium Paris 2008
Slides Aquarium Paris 2008Slides Aquarium Paris 2008
Slides Aquarium Paris 2008
 
PhD Defense
PhD DefensePhD Defense
PhD Defense
 
IzPack Glassfish Lightning Talks 2008
IzPack Glassfish Lightning Talks 2008IzPack Glassfish Lightning Talks 2008
IzPack Glassfish Lightning Talks 2008
 

Recently uploaded

UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 

Recently uploaded (20)

UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 

Java 7 JUG Summer Camp

  • 1. Java SE 7 JUG SummerCamp 2011 La Rochelle, France
  • 3. Fork / Join Project Coin NIO.2 invokedynamic (...)
  • 5. java.lang.Thread java.lang.Runnable wait() <5 notify() synchronized
  • 6. Thread thread = new Thread() { public void run() { System.out.println(">>> Hello!"); } }; thread.start(); thread.join();
  • 7. java.util.concurrent executors concurrent queues concurrent collections atomic variables 5, 6 synchronization patterns rich locks
  • 8. class Sum implements Callable<Long> { private final long from; private final long to; Sum(long from, long to) { this.from = from; this.to = to; } public Long call() { long acc = 0; for (long i = from; i <= to; i++) { acc = acc + i; } return acc; } }
  • 9. ExecutorService executor = Executors.newFixedThreadPool(2); List<Future<Long>> results = executor.invokeAll(asList( new Sum(0, 10), new Sum(100, 1000), new Sum(10000, 1000000) )); for (Future<Long> result : results) { System.out.println(result.get()); }
  • 10. 1.0 Threads made easy 1.1 1.2 1.3 1.4 5 Concurrency made easier 6 7 Parallelism made easier
  • 11. Sum of an array n1 n2 n3 n4 n5 n6 n7 n8 n9 ... ... ... ... sum1 sum2 sum3 sum1 + sum2 sum3 + (...) total sum
  • 12. How many occurrences of “java.util.List” in this filesystem tree?
  • 13. Load into RAM (1 thread) Folder Document subfolders: List<Folder> lines: List<String> documents: List<Document> Divide & conquer (#cores threads)
  • 14. ForkJoinPool Your work Thread management Split Maximize parallelism Fork subtasks Work stealing Join subtasks Compose results
  • 15. ForkJoinTask join() join() RecursiveAction fork() fork() vs RecursiveTask Child ForkJoinTask Child ForkJoinTask
  • 16. 16 Folder word counting task 10 5 1 Document word Document word Folder word counting task counting task counting task 3 2 fork() Document word Document word n join() counting task counting task
  • 18. Speedup& 7" 6" 5" 4" 3" 2" 1" 2" 4" 6" 8" 10" 12" #cores
  • 19. No I/O No synchronization / locks Decompose in simple recursive tasks Do not decompose below a threshold Take advantage of multicores with no pain You have more F/J candidate algorithms than you think!
  • 21. private void writeSomeData() throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); out.close(); }
  • 22. private void writeSomeData() throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); out.close(); } what if...
  • 23. private void writeSomeData() throws IOException { DataOutputStream out = null; try { out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); } finally { if (out != null) { out.close(); } } }
  • 24. private void writeSomeData() throws IOException { DataOutputStream out = null; try { out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); } finally { if (out != null) { out.close(); } } } ...this is still far from correct!
  • 25. try ( FileOutputStream out = new FileOutputStream("output"); FileInputStream in1 = new FileInputStream(“input1”); FileInputStream in2 = new FileInputStream(“input2”) ) { // Do something useful with those 3 streams! // out, in1 and in2 will be closed in any case out.write(in1.read()); out.write(in2.read()); }
  • 26. public class AutoClose implements AutoCloseable { @Override public void close() { System.out.println(">>> close()"); throw new RuntimeException("Exception in close()"); } public void work() throws MyException { System.out.println(">>> work()"); throw new MyException("Exception in work()"); } }
  • 27. AutoClose autoClose = new AutoClose(); try { autoClose.work(); } finally { autoClose.close(); }
  • 28. AutoClose autoClose = new AutoClose(); try { autoClose.work(); } finally { autoClose.close(); } >>> work() >>> close() java.lang.RuntimeException: Exception in close()        at AutoClose.close(AutoClose.java:6)        at AutoClose.runWithMasking(AutoClose.java:19)        at AutoClose.main(AutoClose.java:52)
  • 29. AutoClose autoClose = new AutoClose(); try { autoClose.work(); } finally { autoClose.close(); } MyException m asked by Run >>> work() time Exception >>> close() java.lang.RuntimeException: Exception in close()        at AutoClose.close(AutoClose.java:6)        at AutoClose.runWithMasking(AutoClose.java:19)        at AutoClose.main(AutoClose.java:52)
  • 30. “Caused by” ≠ “Also happened”
  • 31. AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
  • 32. AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
  • 33. AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
  • 34. AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
  • 35. AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
  • 36. try (AutoClose autoClose = new AutoClose()) { autoClose.work(); }
  • 37. try (AutoClose autoClose = new AutoClose()) { autoClose.work(); } >>> work() >>> close() MyException: Exception in work()        at AutoClose.work(AutoClose.java:11)        at AutoClose.main(AutoClose.java:16)        Suppressed: java.lang.RuntimeException: Exception in close()               at AutoClose.close(AutoClose.java:6)               at AutoClose.main(AutoClose.java:17)
  • 38. public void compress(String input, String output) throws IOException { try( FileInputStream fin = new FileInputStream(input); FileOutputStream fout = new FileOutputStream(output); GZIPOutputStream out = new GZIPOutputStream(fout) ) { byte[] buffer = new byte[4096]; int nread = 0; while ((nread = fin.read(buffer)) != -1) { out.write(buffer, 0, nread); } } }
  • 39. public void compress(String input, String output) throws IOException { public void compress(String paramString1, String paramString2) try(         throws IOException { FileInputStream fin = new FileInputStream(input);     FileInputStream localFileInputStream = new FileInputStream(paramString1); FileOutputStream fout = new FileOutputStream(output);     Object localObject1 = null; GZIPOutputStream out = new GZIPOutputStream(fout)     try { ) {         FileOutputStream localFileOutputStream = new FileOutputStream(paramString2); byte[] buffer = new byte[4096];         Object localObject2 = null; int nread = 0;         try { while ((nread = fin.read(buffer)) != -1) {             GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localFileOutputStream); out.write(buffer, 0, nread);             Object localObject3 = null; }             try { }                 byte[] arrayOfByte = new byte[4096]; }                 int i = 0;                 while ((i = localFileInputStream.read(arrayOfByte)) != -1) {                     localGZIPOutputStream.write(arrayOfByte, 0, i);                 }             } catch (Throwable localThrowable6) {                 localObject3 = localThrowable6;                 throw localThrowable6;             } finally {                 if (localGZIPOutputStream != null) {                     if (localObject3 != null) {                         try {                             localGZIPOutputStream.close();                         } catch (Throwable localThrowable7) {                             localObject3.addSuppressed(localThrowable7);                         }                     } else {                         localGZIPOutputStream.close();                     }                 }             }         } catch (Throwable localThrowable4) {             localObject2 = localThrowable4;             throw localThrowable4;         } finally {             if (localFileOutputStream != null) {                 if (localObject2 != null) {                     try {                         localFileOutputStream.close();                     } catch (Throwable localThrowable8) {                         localObject2.addSuppressed(localThrowable8);                     }                 } else {                     localFileOutputStream.close();                 }             }         }     } catch (Throwable localThrowable2) {         localObject1 = localThrowable2;         throw localThrowable2;     } finally {         if (localFileInputStream != null) {             if (localObject1 != null) {                 try {                     localFileInputStream.close();                 } catch (Throwable localThrowable9) {                     localObject1.addSuppressed(localThrowable9);                 }             } else {                 localFileInputStream.close();             }         }     } }
  • 40. Not just syntactic sugar Clutter-free, correct code close(): - be more specific than java.lang.Exception - no exception if it can’t fail - no exception that shall not be suppressed (e.g., java.lang.InterruptedException)
  • 42. List<String> strings = new LinkedList<Integer>(); Map<String, List<String>> contacts = new HashMap<Integer, String>();
  • 43. List<String> strings = new LinkedList<String>(); strings.add("hello"); strings.add("world"); Map<String, List<String>> contacts = new HashMap<String, List<String>>(); contacts.put("Julien", new LinkedList<String>()); contacts.get("Julien").addAll(asList("Foo", "Bar", "Baz"));
  • 44. List<String> strings = new LinkedList<>(); strings.add("hello"); strings.add("world"); Map<String, List<String>> contacts = new HashMap<>(); contacts.put("Julien", new LinkedList<String>()); contacts.get("Julien").addAll(asList("Foo", "Bar", "Baz"));
  • 45. Map<String, String> map = new HashMap<String, String>() { { put("foo", "bar"); put("bar", "baz"); } };
  • 46. Map<String, String> map = new HashMap<>() { { put("foo", "bar"); put("bar", "baz"); } };
  • 47. Map<String, String> map = new HashMap<>() { { put("foo", "bar"); put("bar", "baz"); } }; Diamond.java:43: error: cannot infer type arguments for HashMap; Map<String, String> map = new HashMap<>() { ^ reason: cannot use '<>' with anonymous inner classes 1 error
  • 48. class SomeClass<T extends Serializable & CharSequence> { } Non-denotable type
  • 49. class SomeClass<T extends Serializable & CharSequence> { } Non-denotable type SomeClass<?> foo = new SomeClass<String>(); SomeClass<?> fooInner = new SomeClass<String>() { }; SomeClass<?> bar = new SomeClass<>(); SomeClass<?> bar = new SomeClass<>() { };
  • 50. class SomeClass<T extends Serializable & CharSequence> { } Non-denotable type SomeClass<?> foo = new SomeClass<String>(); SomeClass<?> fooInner = new SomeClass<String>() { }; SomeClass<?> bar = new SomeClass<>(); SomeClass<?> bar = new SomeClass<>() { }; No denotable type to generate a class
  • 51. Less ceremony when using generics No diamond with inner classes
  • 53. private static <T> void doSomethingBad(List<T> list, T... values) { values[0] = list.get(0); } public static void main(String[] args) { List list = Arrays.asList("foo", "bar", "baz"); doSomethingBad(list, 1, 2, 3); }
  • 54. This yields warnings + crash: private static <T> void doSomethingBad(List<T> list, T... values) { values[0] = list.get(0); } public static void main(String[] args) { List list = Arrays.asList("foo", "bar", "baz"); doSomethingBad(list, 1, 2, 3); } Heap Pollution: List = List<String>
  • 55. private static <T> void doSomethingGood(List<T> list, T... values) { for (T value : values) { list.add(value); } }
  • 56. private static <T> void doSomethingGood(List<T> list, T... values) { for (T value : values) { list.add(value); } } $ javac Good.java Note: Good.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
  • 57. @SuppressWarnings({“unchecked”,“varargs”}) public static void main(String[] args) { List<String> list = new LinkedList<>(); doSomethingGood(list, "hi", "there", "!"); } $ javac Good.java $
  • 58. static, final methods, constructors @SafeVarargs private static <T> void doSomethingGood(List<T> list, T... values) { for (T value : values) { list.add(value); } }
  • 59. Mark your code as safe for varargs You can’t cheat with @SafeVarags Remove @SuppressWarnings in client code and pay attention to real warnings
  • 60. Multi-catch & more precise rethrow
  • 61. Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance));
  • 62. try { Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance)); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }
  • 63. try { Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance)); } catch (Throwable t) { t.printStackTrace(); }
  • 64. try { Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance)); } catch (Throwable t) { t.printStackTrace(); } How about SecurityException?
  • 65. try { Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance)); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } Union of alternatives
  • 66. catch (SomeException e) Now implicitly final unless assigned...
  • 67. static class SomeRootException extends Exception { } static class SomeChildException extends SomeRootException { } static class SomeOtherChildException extends SomeRootException { } public static void main(String... args) throws Throwable { try { throw new SomeChildException(); } catch (SomeRootException firstException) { try { throw firstException; } catch (SomeOtherChildException secondException) { System.out.println("I got you!"); } }
  • 68. static class SomeRootException extends Exception { } static class SomeChildException extends SomeRootException { } static class SomeOtherChildException extends SomeRootException { } public static void main(String... args) throws Throwable { try { throw new SomeChildException(); } catch (SomeRootException firstException) { try { throw firstException; } catch (SomeOtherChildException secondException) { System.out.println("I got you!"); } } $ javac Imprecise.java Imprecise.java:13: error: exception SomeOtherChildException is never thrown in body of corresponding try statement } catch (SomeOtherChildException secondException) { ^ 1 error
  • 69. Less clutter Be precise Do not capture unintended exceptions Better exception flow analysis
  • 71. // 123 in decimal, octal, hexadecimal and binary byte decimal = 123; byte octal = 0_173; byte hexadecimal = 0x7b; byte binary = 0b0111_1011; // Other values double doubleValue = 1.111_222_444F; long longValue = 1_234_567_898L; long longHexa = 0x1234_3b3b_0123_cdefL;
  • 72. public static boolean isTrue(String str) { switch(str.trim().toUpperCase()) { case "OK": case "YES": case "TRUE": return true; case "KO": case "NO": case "FALSE": return false; default: throw new IllegalArgumentException("Not a valid true/false string."); } }
  • 73. public static boolean isTrue(String s) { String str = s.trim().toUpperCase(); int jump = -1; switch(str.hashCode()) { case 2404: if (str.equals("KO")) { jump = 3; Bucket } break; (...) switch(jump) { (...) case 3: case 4: case 5: return false; default: Real code throw new IllegalArgumentException( "Not a valid true/false string."); } }
  • 74. Oracle Technology Network (more soon...) Fork and Join: Java Can Excel at Painless Parallel Programming Too! http://goo.gl/tostz Better Resource Management with Java SE 7: Beyond Syntactic Sugar http://goo.gl/7ybgr
  • 75. Julien Ponge @jponge http://gplus.to/jponge http://julien.ponge.info/ julien.ponge@insa-lyon.fr