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

The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecturehugo lu
 
Desenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcadosDesenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcadosRodrigo Almeida
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language安齊 劉
 
Ch05 cpu-scheduling
Ch05 cpu-schedulingCh05 cpu-scheduling
Ch05 cpu-schedulingNazir Ahmed
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithmssathish sak
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
The Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPThe Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPGregor Schmidt
 
A python web service
A python web serviceA python web service
A python web serviceTemian Vlad
 
Process Synchronization in operating system | mutex | semaphore | race condition
Process Synchronization in operating system | mutex | semaphore | race conditionProcess Synchronization in operating system | mutex | semaphore | race condition
Process Synchronization in operating system | mutex | semaphore | race conditionShivam Mitra
 
Network Traffic Analysis With Wireshark.pptx
Network Traffic Analysis With Wireshark.pptxNetwork Traffic Analysis With Wireshark.pptx
Network Traffic Analysis With Wireshark.pptxArifinChowdhury2
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRAJU MAKWANA
 
Rouault imbert alpc_rpc_pacsec
Rouault imbert alpc_rpc_pacsecRouault imbert alpc_rpc_pacsec
Rouault imbert alpc_rpc_pacsecPacSecJP
 
Networking basics and basic cisco commands
Networking basics and basic cisco commandsNetworking basics and basic cisco commands
Networking basics and basic cisco commandsKrishna Mohan
 

La actualidad más candente (20)

The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecture
 
Desenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcadosDesenvolvimento de drivers para sistemas embarcados
Desenvolvimento de drivers para sistemas embarcados
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
Java I/O
Java I/OJava I/O
Java I/O
 
Ch05 cpu-scheduling
Ch05 cpu-schedulingCh05 cpu-scheduling
Ch05 cpu-scheduling
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithms
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
String in java
String in javaString in java
String in java
 
The Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPThe Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEP
 
A python web service
A python web serviceA python web service
A python web service
 
RTOS - Real Time Operating Systems
RTOS - Real Time Operating SystemsRTOS - Real Time Operating Systems
RTOS - Real Time Operating Systems
 
Process Synchronization in operating system | mutex | semaphore | race condition
Process Synchronization in operating system | mutex | semaphore | race conditionProcess Synchronization in operating system | mutex | semaphore | race condition
Process Synchronization in operating system | mutex | semaphore | race condition
 
Network Traffic Analysis With Wireshark.pptx
Network Traffic Analysis With Wireshark.pptxNetwork Traffic Analysis With Wireshark.pptx
Network Traffic Analysis With Wireshark.pptx
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
4 threads
4 threads4 threads
4 threads
 
Rouault imbert alpc_rpc_pacsec
Rouault imbert alpc_rpc_pacsecRouault imbert alpc_rpc_pacsec
Rouault imbert alpc_rpc_pacsec
 
Networking basics and basic cisco commands
Networking basics and basic cisco commandsNetworking basics and basic cisco commands
Networking basics and basic cisco commands
 
Process scheduling linux
Process scheduling linuxProcess scheduling linux
Process scheduling linux
 

Similar a Fork and join framework

Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
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 8EPAM_Systems_Bulgaria
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin 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 TasksWO Community
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvmaragozin
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
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...Víctor Bolinches
 

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

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 

Último (20)

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 

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.