SlideShare a Scribd company logo
Java SE 7
     Fork / Join Framework
Language Evolutions (Project Coin)




                                     Julien Ponge
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
A need for divide and conquer
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
class FolderSearchTask extends RecursiveTask<Long> {
(...)

  protected Long compute() {
    long count = 0L;
    List<RecursiveTask<Long>> forks = new LinkedList<>();

      for (Folder subFolder : folder.getSubFolders()) {
        FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
        forks.add(task);
        task.fork();
      }
      for (Document document : folder.getDocuments()) {
        DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
        forks.add(task);
        task.fork();
      }

      for (RecursiveTask<Long> task : forks) {
        count = count + task.join();
      }
      return count;
  }

(...)
}
class FolderSearchTask extends RecursiveTask<Long> {
(...)

  protected Long compute() {
    long count = 0L;
    List<RecursiveTask<Long>> forks = new LinkedList<>();                   Split
      for (Folder subFolder : folder.getSubFolders()) {
        FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
        forks.add(task);
        task.fork();
      }
      for (Document document : folder.getDocuments()) {
        DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
        forks.add(task);
        task.fork();
      }

      for (RecursiveTask<Long> task : forks) {
        count = count + task.join();
      }
      return count;
  }

(...)
}
class FolderSearchTask extends RecursiveTask<Long> {
(...)

  protected Long compute() {
    long count = 0L;
    List<RecursiveTask<Long>> forks = new LinkedList<>();

      for (Folder subFolder : folder.getSubFolders()) {
        FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
        forks.add(task);

      }
        task.fork();
                          Fork
      for (Document document : folder.getDocuments()) {
        DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
        forks.add(task);
        task.fork();
      }

      for (RecursiveTask<Long> task : forks) {
        count = count + task.join();
      }
      return count;
  }

(...)
}
class FolderSearchTask extends RecursiveTask<Long> {
(...)

  protected Long compute() {
    long count = 0L;
    List<RecursiveTask<Long>> forks = new LinkedList<>();

      for (Folder subFolder : folder.getSubFolders()) {
        FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
        forks.add(task);
        task.fork();
      }
      for (Document document : folder.getDocuments()) {
        DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
        forks.add(task);
        task.fork();
      }

      for (RecursiveTask<Long> task : forks) {
        count = count + task.join();
      }
      return count;                              Join, Compose
  }

(...)
}
(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://julien.ponge.info/
julien.ponge@insa-lyon.fr

More Related Content

What's hot (17)

PDF
Spock: A Highly Logical Way To Test
Howard Lewis Ship
 
PDF
Conf soat tests_unitaires_Mockito_jUnit_170113
SOAT
 
PPTX
Jdk 7 4-forkjoin
knight1128
 
PDF
Advanced Java Practical File
Soumya Behera
 
PDF
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
PDF
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
PDF
The Ring programming language version 1.5.4 book - Part 79 of 185
Mahmoud Samir Fayed
 
PDF
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
PPT
Thread
phanleson
 
PDF
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
PPTX
Smarter Testing with Spock
Dmitry Voloshko
 
PDF
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
PPTX
Migrating to JUnit 5
Rafael Winterhalter
 
PDF
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
PDF
#JavaFX.forReal() - ElsassJUG
Thierry Wasylczenko
 
PDF
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Spock: A Highly Logical Way To Test
Howard Lewis Ship
 
Conf soat tests_unitaires_Mockito_jUnit_170113
SOAT
 
Jdk 7 4-forkjoin
knight1128
 
Advanced Java Practical File
Soumya Behera
 
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Use of Apache Commons and Utilities
Pramod Kumar
 
The Ring programming language version 1.5.4 book - Part 79 of 185
Mahmoud Samir Fayed
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
Thread
phanleson
 
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
Smarter Testing with Spock
Dmitry Voloshko
 
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Migrating to JUnit 5
Rafael Winterhalter
 
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
#JavaFX.forReal() - ElsassJUG
Thierry Wasylczenko
 
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 

Viewers also liked (10)

PDF
Java Day-5
People Strategists
 
PPTX
Java class 3
Edureka!
 
PPTX
Java class 6
Edureka!
 
PDF
Multiprocessing with python
Patrick Vergain
 
PDF
Threads concept in java
Muthukumaran Subramanian
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPTX
Multithread Programing in Java
M. Raihan
 
ODP
Multithreading In Java
parag
 
PPTX
Multithreading in java
Raghu nath
 
PPT
Java multi threading
Raja Sekhar
 
Java Day-5
People Strategists
 
Java class 3
Edureka!
 
Java class 6
Edureka!
 
Multiprocessing with python
Patrick Vergain
 
Threads concept in java
Muthukumaran Subramanian
 
Multithread Programing in Java
M. Raihan
 
Multithreading In Java
parag
 
Multithreading in java
Raghu nath
 
Java multi threading
Raja Sekhar
 
Ad

Similar to Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Project Coin. (20)

PDF
Java 7 LavaJUG
julien.ponge
 
PDF
JAVA SE 7
Sajid Mehmood
 
KEY
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
PDF
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
PPTX
Fork and join framework
Minh Tran
 
ODP
Java 7 new features
Aliaksandr Kazlou
 
PDF
Java fork join
Masud Hasan
 
PDF
A Java Fork_Join Framework
Hiroshi Ono
 
ODP
Java 7 Features and Enhancements
Gagan Agrawal
 
PDF
Time Travel - Predicting the Future and Surviving a Parallel Universe - JDC2012
Hossam Karim
 
KEY
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
PPTX
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
PDF
C# Advanced L04-Threading
Mohammad Shaker
 
KEY
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
ODP
Concurrent Programming in Java
Ruben Inoto Soto
 
PDF
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
PPT
JDK1.7 features
india_mani
 
ODP
Groovy intro for OUDL
J David Beutel
 
PDF
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Java 7 LavaJUG
julien.ponge
 
JAVA SE 7
Sajid Mehmood
 
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
Fork and join framework
Minh Tran
 
Java 7 new features
Aliaksandr Kazlou
 
Java fork join
Masud Hasan
 
A Java Fork_Join Framework
Hiroshi Ono
 
Java 7 Features and Enhancements
Gagan Agrawal
 
Time Travel - Predicting the Future and Surviving a Parallel Universe - JDC2012
Hossam Karim
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
C# Advanced L04-Threading
Mohammad Shaker
 
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Concurrent Programming in Java
Ruben Inoto Soto
 
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
JDK1.7 features
india_mani
 
Groovy intro for OUDL
J David Beutel
 
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Ad

More from julien.ponge (9)

PDF
AlpesJUG - Communautés opensource, stratégies et écueils
julien.ponge
 
PDF
IzPack at LyonJUG'11
julien.ponge
 
PDF
FOSS - PoitouJUG
julien.ponge
 
PDF
IzPack - PoitouJUG
julien.ponge
 
PDF
IzPack at Devoxx 2010
julien.ponge
 
PDF
IzPack - fOSSa 2009
julien.ponge
 
PDF
Slides Aquarium Paris 2008
julien.ponge
 
PDF
PhD Defense
julien.ponge
 
PDF
IzPack Glassfish Lightning Talks 2008
julien.ponge
 
AlpesJUG - Communautés opensource, stratégies et écueils
julien.ponge
 
IzPack at LyonJUG'11
julien.ponge
 
FOSS - PoitouJUG
julien.ponge
 
IzPack - PoitouJUG
julien.ponge
 
IzPack at Devoxx 2010
julien.ponge
 
IzPack - fOSSa 2009
julien.ponge
 
Slides Aquarium Paris 2008
julien.ponge
 
PhD Defense
julien.ponge
 
IzPack Glassfish Lightning Talks 2008
julien.ponge
 

Recently uploaded (15)

PDF
cyanean_Lab_Reportdfd dfdsfsdfsd f dsf.pdf
REYESTACZAEDGARALEJA
 
PDF
How Modern Filmmakers Plan, Shoot, and Deliver Blockbuster Movies.pdf
All Writers Destination
 
PPTX
Line Up Activity For Kids and Adult.....
cynthiamarasigan
 
PDF
Blake and Mortimer 01 The Secret of the Swordfish
SuperDrive16
 
PPTX
一比一原版(Newman毕业证)纽曼大学毕业证如何办理
Taqyea
 
PPT
How Bokep Indo Impacts Relationships and Social Norms in Indonesia
roohinxt
 
PPTX
HARASSMENT IN WORKPLACE FOR DEEP KNOWLEDGE
ashishmalikp2426
 
PPTX
beat and rhythm for school, mapeh 3 wisdom
MarkAnthonySarsua
 
PPTX
plantilla-animada-netflix-en-power-point.pptx
CarmenGarca710436
 
PPTX
Most Played Songs on YouTube 2025 Edition.pptx
Marco Wilson
 
PPTX
Fun Friday for corporate virtual fridays
chandana94smiles
 
PDF
Mommy J. At San Vicente Ward (Group 1)).pdf
MitsuriKanroji22
 
PPT
chapter 10.pptkkkkkkkkkkkkkkkkkkkkkkkkkk
trishalasharma7
 
PPTX
Hunka Hunka Burnin’ Love Prototype Website 2013
Cheryl M
 
PPTX
ANKITA PPT FINAL.pptx....................
PriyalSharma25
 
cyanean_Lab_Reportdfd dfdsfsdfsd f dsf.pdf
REYESTACZAEDGARALEJA
 
How Modern Filmmakers Plan, Shoot, and Deliver Blockbuster Movies.pdf
All Writers Destination
 
Line Up Activity For Kids and Adult.....
cynthiamarasigan
 
Blake and Mortimer 01 The Secret of the Swordfish
SuperDrive16
 
一比一原版(Newman毕业证)纽曼大学毕业证如何办理
Taqyea
 
How Bokep Indo Impacts Relationships and Social Norms in Indonesia
roohinxt
 
HARASSMENT IN WORKPLACE FOR DEEP KNOWLEDGE
ashishmalikp2426
 
beat and rhythm for school, mapeh 3 wisdom
MarkAnthonySarsua
 
plantilla-animada-netflix-en-power-point.pptx
CarmenGarca710436
 
Most Played Songs on YouTube 2025 Edition.pptx
Marco Wilson
 
Fun Friday for corporate virtual fridays
chandana94smiles
 
Mommy J. At San Vicente Ward (Group 1)).pdf
MitsuriKanroji22
 
chapter 10.pptkkkkkkkkkkkkkkkkkkkkkkkkkk
trishalasharma7
 
Hunka Hunka Burnin’ Love Prototype Website 2013
Cheryl M
 
ANKITA PPT FINAL.pptx....................
PriyalSharma25
 

Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Project Coin.

  • 1. Java SE 7 Fork / Join Framework Language Evolutions (Project Coin) Julien Ponge
  • 3. java.lang.Thread java.lang.Runnable wait() <5 notify() synchronized
  • 4. Thread thread = new Thread() { public void run() { System.out.println(">>> Hello!"); } }; thread.start(); thread.join();
  • 5. java.util.concurrent executors concurrent queues concurrent collections atomic variables 5, 6 synchronization patterns rich locks
  • 6. 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; } }
  • 7. 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()); }
  • 8. 1.0 Threads made easy 1.1 1.2 1.3 1.4 5 Concurrency made easier 6 7 Parallelism made easier
  • 9. Sum of an array n1 n2 n3 n4 n5 n6 n7 n8 n9 ... ... ... ... sum1 sum2 sum3 sum1 + sum2 sum3 + (...) total sum
  • 10. A need for divide and conquer
  • 11. ForkJoinPool Your work Thread management Split Maximize parallelism Fork subtasks Work stealing Join subtasks Compose results
  • 12. ForkJoinTask join() join() RecursiveAction fork() fork() vs RecursiveTask Child ForkJoinTask Child ForkJoinTask
  • 13. 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
  • 14. class FolderSearchTask extends RecursiveTask<Long> { (...) protected Long compute() { long count = 0L; List<RecursiveTask<Long>> forks = new LinkedList<>(); for (Folder subFolder : folder.getSubFolders()) { FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord); forks.add(task); task.fork(); } for (Document document : folder.getDocuments()) { DocumentSearchTask task = new DocumentSearchTask(document, searchedWord); forks.add(task); task.fork(); } for (RecursiveTask<Long> task : forks) { count = count + task.join(); } return count; } (...) }
  • 15. class FolderSearchTask extends RecursiveTask<Long> { (...) protected Long compute() { long count = 0L; List<RecursiveTask<Long>> forks = new LinkedList<>(); Split for (Folder subFolder : folder.getSubFolders()) { FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord); forks.add(task); task.fork(); } for (Document document : folder.getDocuments()) { DocumentSearchTask task = new DocumentSearchTask(document, searchedWord); forks.add(task); task.fork(); } for (RecursiveTask<Long> task : forks) { count = count + task.join(); } return count; } (...) }
  • 16. class FolderSearchTask extends RecursiveTask<Long> { (...) protected Long compute() { long count = 0L; List<RecursiveTask<Long>> forks = new LinkedList<>(); for (Folder subFolder : folder.getSubFolders()) { FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord); forks.add(task); } task.fork(); Fork for (Document document : folder.getDocuments()) { DocumentSearchTask task = new DocumentSearchTask(document, searchedWord); forks.add(task); task.fork(); } for (RecursiveTask<Long> task : forks) { count = count + task.join(); } return count; } (...) }
  • 17. class FolderSearchTask extends RecursiveTask<Long> { (...) protected Long compute() { long count = 0L; List<RecursiveTask<Long>> forks = new LinkedList<>(); for (Folder subFolder : folder.getSubFolders()) { FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord); forks.add(task); task.fork(); } for (Document document : folder.getDocuments()) { DocumentSearchTask task = new DocumentSearchTask(document, searchedWord); forks.add(task); task.fork(); } for (RecursiveTask<Long> task : forks) { count = count + task.join(); } return count; Join, Compose } (...) }
  • 19. Speedup& 7" 6" 5" 4" 3" 2" 1" 2" 4" 6" 8" 10" 12" #cores
  • 20. 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!
  • 22. private void writeSomeData() throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); out.close(); }
  • 23. private void writeSomeData() throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream("data")); out.writeInt(666); out.writeUTF("Hello"); out.close(); } what if...
  • 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(); } } }
  • 25. 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!
  • 26. 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()); }
  • 27. 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()"); } }
  • 28. AutoClose autoClose = new AutoClose(); try { autoClose.work(); } finally { autoClose.close(); }
  • 29. 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)
  • 30. 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)
  • 31. “Caused by” ≠ “Also happened”
  • 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. 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(); } }
  • 37. try (AutoClose autoClose = new AutoClose()) { autoClose.work(); }
  • 38. 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)
  • 39. 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); } } }
  • 40. 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();             }         }     } }
  • 41. 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)
  • 43. List<String> strings = new LinkedList<Integer>(); Map<String, List<String>> contacts = new HashMap<Integer, String>();
  • 44. 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"));
  • 45. 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"));
  • 46. Map<String, String> map = new HashMap<String, String>() { { put("foo", "bar"); put("bar", "baz"); } };
  • 47. Map<String, String> map = new HashMap<>() { { put("foo", "bar"); put("bar", "baz"); } };
  • 48. 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
  • 49. class SomeClass<T extends Serializable & CharSequence> { } Non-denotable type
  • 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<>() { };
  • 51. 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
  • 52. Less ceremony when using generics No diamond with inner classes
  • 54. 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); }
  • 55. 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>
  • 56. private static <T> void doSomethingGood(List<T> list, T... values) { for (T value : values) { list.add(value); } }
  • 57. 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.
  • 58. @SuppressWarnings({“unchecked”,“varargs”}) public static void main(String[] args) { List<String> list = new LinkedList<>(); doSomethingGood(list, "hi", "there", "!"); } $ javac Good.java $
  • 59. static, final methods, constructors @SafeVarargs private static <T> void doSomethingGood(List<T> list, T... values) { for (T value : values) { list.add(value); } }
  • 60. Mark your code as safe for varargs You can’t cheat with @SafeVarags Remove @SuppressWarnings in client code and pay attention to real warnings
  • 61. Multi-catch & more precise rethrow
  • 62. Class<?> stringClass = Class.forName("java.lang.String"); Object instance = stringClass.newInstance(); Method toStringMethod = stringClass.getMethod("toString"); System.out.println(toStringMethod.invoke(instance));
  • 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 (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.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(); }
  • 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 (Throwable t) { t.printStackTrace(); } How about SecurityException?
  • 66. 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
  • 67. catch (SomeException e) Now implicitly final unless assigned...
  • 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!"); } }
  • 69. 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
  • 70. Less clutter Be precise Do not capture unintended exceptions Better exception flow analysis
  • 72. // 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;
  • 73. 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."); } }
  • 74. 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."); } }
  • 75. 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
  • 76. Julien Ponge @jponge http://julien.ponge.info/ [email protected]