SlideShare una empresa de Scribd logo
1 de 13
FORK AND JOIN
FRAMEWORK
Minh Tran – 11/2012
Some History
• Until recently, most computers only had 1 processing core
• Multithreading was simulated on a single core
• Not true concurrency
• Serial approach to algorithms often sufficed
Multi-core
• Concurrency and performance are tied together
• Real concurrency – separate threads can execute on
  different cores at the same time
• The JVM runtime controls scheduling
Plain Old Threads
Thread thread = new Thread() {
   @Override public void run() {
     System.out.println(">>> I am running in a separate thread!");
   }
};
thread.start();
thread.join();
Another example with java.util.concurrent
import java.util.*;                           public static void main(String[] args) throws Exception {
import java.util.concurrent.*;                     ExecutorService executor = Executors.newFixedThreadPool(2);
import static java.util.Arrays.asList;             List <Future<Long>> results = executor.invokeAll(asList(
                                                       new Sum(0, 10), new Sum(100, 1_000), new Sum(10_000,
public class Sums {                           1_000_000)
  static class Sum implements                      ));
Callable<Long> {                                   executor.shutdown();
     private final long from;
     private final long to;                           for (Future<Long> result : results) {
        Sum(long from, long to) {                        System.out.println(result.get());
        this.from = from;                             }
        this.to = to;                             }
     }                                        }
     @Override
     public Long call() {
        long acc = 0;
        for (long i = from; i <= to; i++) {
           acc = acc + i;
        }
        return acc;
     }
  }
Fork and Join Framework
• Some types of algorithms exist that
  require tasks to create subtasks and
  communicate with each other to
  complete.
• Those are the “divide and conquer”
  algorithms, which are also referred to
  as “map and reduce,”
Fork and Join Framework (cont.)
• Example: partial sums of an Array of Integers




• Solving the problem above with executors is easy:
  • Divide the array into the number n of available physical processing
    units
  • Create Callable instances to compute each partial sum
  • Submit them to an executor managing a pool of n threads
  • Collect the result to compute the final sum.
Fork and Join Framework (cont.)
• The core addition is a new ForkJoinPool executor that is
  dedicated to running instances
  implementing ForkJoinTask.
• ForkJoinTask objects feature two specific methods:
  • fork(): allows a ForkJoinTask to be planned for asynchronous
    execution
  • join() method allows a ForkJoinTask to wait for the completion of
    another one.
• There are 2 types of ForkJoinTask:
  • RecursiveAction represent executions that do not yield a return
    value.
  • Instances RecursiveTask yields return values.
Demo / Q&A
Summary
• Strong focus on the new fork/join tasks provided by Java
 SE 7 for making it easier to write parallel programs
Reference
• http://www.oracle.com/technetwork/articles/java/fork-join-
  422606.html
• http://www.ibm.com/developerworks/java/library/j-
  jtp11137/index.html
Thank You

Más contenido relacionado

La actualidad más candente

Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
myrajendra
 

La actualidad más candente (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Ch 4 linker loader
Ch 4 linker loaderCh 4 linker loader
Ch 4 linker loader
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Np cooks theorem
Np cooks theoremNp cooks theorem
Np cooks theorem
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 

Similar a Fork and join framework

13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
EPAM_Systems_Bulgaria
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
WO Community
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
aragozin
 

Similar a Fork and join framework (20)

Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Thread
ThreadThread
Thread
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
 
分散式系統
分散式系統分散式系統
分散式系統
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Concurrency-5.pdf
Concurrency-5.pdfConcurrency-5.pdf
Concurrency-5.pdf
 
Operating System lab
Operating System labOperating System lab
Operating System lab
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Último (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Fork and join framework

  • 1. FORK AND JOIN FRAMEWORK Minh Tran – 11/2012
  • 2. Some History • Until recently, most computers only had 1 processing core • Multithreading was simulated on a single core • Not true concurrency • Serial approach to algorithms often sufficed
  • 3. Multi-core • Concurrency and performance are tied together • Real concurrency – separate threads can execute on different cores at the same time • The JVM runtime controls scheduling
  • 4. Plain Old Threads Thread thread = new Thread() { @Override public void run() { System.out.println(">>> I am running in a separate thread!"); } }; thread.start(); thread.join();
  • 5. Another example with java.util.concurrent import java.util.*; public static void main(String[] args) throws Exception { import java.util.concurrent.*; ExecutorService executor = Executors.newFixedThreadPool(2); import static java.util.Arrays.asList; List <Future<Long>> results = executor.invokeAll(asList( new Sum(0, 10), new Sum(100, 1_000), new Sum(10_000, public class Sums { 1_000_000) static class Sum implements )); Callable<Long> { executor.shutdown(); private final long from; private final long to; for (Future<Long> result : results) { Sum(long from, long to) { System.out.println(result.get()); this.from = from; } this.to = to; } } } @Override public Long call() { long acc = 0; for (long i = from; i <= to; i++) { acc = acc + i; } return acc; } }
  • 6. Fork and Join Framework • Some types of algorithms exist that require tasks to create subtasks and communicate with each other to complete. • Those are the “divide and conquer” algorithms, which are also referred to as “map and reduce,”
  • 7. Fork and Join Framework (cont.) • Example: partial sums of an Array of Integers • Solving the problem above with executors is easy: • Divide the array into the number n of available physical processing units • Create Callable instances to compute each partial sum • Submit them to an executor managing a pool of n threads • Collect the result to compute the final sum.
  • 8. Fork and Join Framework (cont.) • The core addition is a new ForkJoinPool executor that is dedicated to running instances implementing ForkJoinTask. • ForkJoinTask objects feature two specific methods: • fork(): allows a ForkJoinTask to be planned for asynchronous execution • join() method allows a ForkJoinTask to wait for the completion of another one.
  • 9. • There are 2 types of ForkJoinTask: • RecursiveAction represent executions that do not yield a return value. • Instances RecursiveTask yields return values.
  • 11. Summary • Strong focus on the new fork/join tasks provided by Java SE 7 for making it easier to write parallel programs
  • 12. Reference • http://www.oracle.com/technetwork/articles/java/fork-join- 422606.html • http://www.ibm.com/developerworks/java/library/j- jtp11137/index.html

Notas del editor

  1. All the code in this example does is create a thread that prints a string to the standard output stream.The main thread waits for created (child) thread to complete by calling join().Directly manipulating threads this way is fine for simple examples, but with concurrent programming, such code can quickly become error-prone, especially when several threads need to cooperate to perform a larger task. In such cases, their control flow needs to be coordinated.For example, the completion of a thread’s execution might depend on other threads having completed their execution.The usual well-known example is that of the producer/consumer, because the producer should wait for the consumer if the consumer’s queue is full, and the consumer should wait for the producer when empty.This requirement can be addressed through shared state and condition queues, but you still have to use synchronization byusing java.lang.Object.notify() and java.lang.Object.wait() on shared-state objects, which is easy to get wrong.Finally, a common pitfall is to use synchronize and provide mutual exclusion over large pieces of code or even whole methods. While this approach leads to thread-safe code, it usually yields poor performance due to the limited parallelism that is induced by exclusion being in effect too long.As is often the case in computing, manipulating low-level primitives to implement complex operations opens the door to mistakes, and as such, developers should seek to encapsulate complexity within efficient, higher-level libraries. Java SE 5 provided us with just that ability.
  2. This example program leverages an executor to compute sums of long integers.The Sum class implements the Callable interface that is used by executors for result-bearing computations, and the concurrent work is performed within the call() method. The java.util.concurrent.Executors class provides several utility methods, such as providing pre-configured executors or wrapping plain old java.lang.Runnable objects into instances of Callable.The advantage of using Callable over Runnable is that Callable can explicitly return a value.This example uses an executor that dispatches work over two threads. The ExecutorService.invokeAll() method takes a collection of Callable instances and waits for the completion of all of them before returning.It returns a list of Future objects, which all represent the “future” result of the computation. If we were to work in an asynchronous fashion, we could test each Future object to check whether its corresponding Callable has finished its work and check whether it threw an exception, and we could even cancel it.By contrast, when using plain old threads, you must encode cancellation logic through a shared mutable Boolean and cripple the code with periodic checks over this Boolean.Because invokeAll() is blocking, we can directly iterate over the Future instances and fetch their computed sums.Also note that an executor service must be shut down. If it is not shut down, the Java Virtual Machine will not exit when the main method does, because there will still be active threads around.
  3. Executors are a big step forward compared to plain old threads because executors ease the management of concurrent tasks.The idea is to split the data space to be processed by an algorithm into smaller, independent chunks. That is the “map” phase. In turn, once a set of chunks has been processed, partial results can be collected to form the final result. This is the “reduce” phase.
  4. However, the execution plan often is not so simple. In particular, the “map” phase that identifies chunks of data “small enough” to be processed independently in an efficient manner does not know the data space topology in advance. This is especially true for graph-based and tree-based data structures.In those cases, algorithms should create hierarchies of “divisions,” waiting for subtasks to complete before returning a partial result. Although less optimal in an array like the one in Figure 1, several levels of concurrent partial-sum computations can be used (for example, divide the array into four subtasks on a dual-core processor).The problem with the executors for implementing divide and conquer algorithms is not related to creating subtasks, because a Callable is free to submit a new subtask to its executor and wait for its result in a synchronous or asynchronous fashion. The issue is that of parallelism: When a Callable waits for the result of another Callable, it is put in a waiting state, thus wasting an opportunity to handle another Callable queued for execution.
  5. The fork/join framework added to the java.util.concurrent package in Java SE 7 through Doug Lea’s efforts fills that gap. The Java SE 5 and Java SE 6 versions of java.util.concurrent helped in dealing with concurrency, and the additions in Java SE 7 help with parallelism.