SlideShare una empresa de Scribd logo
1 de 42
ForkJoin




@Sander_Mak
About
Coding      at
                    (           )


  Writing              Blog @
                 branchandbound.net




   Speaking
Agenda
ForkJoin   Setting the scene
           ForkJoin API & Patterns
           Comparisons & Future

           break

 Akka      Introduction
           Actors
           Async IO
Problem?
Problem?
Problem?
Problem?
Problem?


Architectural mismatch
Problem?
So let the compiler/runtime solve it!
Problem?
So let the compiler/runtime solve it!


                                                  n	
  <	
  2




                                  n




if	
  (n	
  <	
  2)	
  
	
  {	
  return	
  n;	
  }
else	
  
	
  {	
  return	
  fib(n	
  -­‐	
  1)	
  +	
  fib(n	
  -­‐	
  2);	
  }
Problem?
So let the compiler/runtime solve it!




                  Unfortunately not in ,
                    but feasible in pure
                 functional languages like
First attempt
	
  	
  	
  	
  public	
  static	
  int	
  fib(final	
  int	
  n)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  if	
  (n	
  <	
  2)	
  {	
  return	
  n;	
  }
	
  	
  	
  	
  	
  	
  	
  	
  else	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  final	
  int[]	
  t1	
  =	
  {0},	
  t2	
  =	
  {0};
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Thread	
  thread1	
  =	
  new	
  Thread()	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  public	
  void	
  run()	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  t1[0]	
  =	
  fib(n	
  -­‐	
  1);
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }	
  };

	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Thread	
  thread2	
  =	
  new	
  Thread()	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  public	
  void	
  run()	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  t2[0]	
  =	
  fib(n	
  -­‐	
  2);
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }	
  };
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  thread1.start();	
  thread2.start();
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  thread1.join();	
  thread2.join();

	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  t1[0]	
  +	
  t2[0];
	
  	
  	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  }                                                                                                              if	
  (n	
  <	
  2)	
  
                                                                                                                               	
  {	
  return	
  n;	
  }
                                                                                                                               else	
  
                                                                                                                               	
  {	
  return	
  fib(n	
  -­‐	
  1)	
  +	
  fib(n	
  -­‐	
  2);	
  }
Threads
Threads are mostly waiting
Improve with threadpooling
 but not by much
 starvation
What if we sum in a new thread?
 synchronization
 visibility issues (Java Memory Model)
ForkJoin
Fork:
Recursively decompose                                       Result = 3
large task into subtasks
                                                                Fib(4)

Join:
                                              Fib(3)                              Fib(2)
Await results of
recursive tasks
and combine                         Fib(2)             Fib(1)            Fib(1)            Fib(0)



                           Fib(1)            Fib(0)
ForkJoin
Introducing:
                            ForkJoinPool
           java.util.concurrent.

       java.util.concurrent.ForkJoinTask
                                                      ForkJoinTask




                                            RecursiveAction   RecursiveTask




 ForkJoinPool:
void                               execute (ForkJoinTask<?>)
T                                  invoke (ForkJoinTask<T>)

	
  	
  
ForkJoin
compute(problem)	
  {
	
  	
  if	
  (problem.size	
  <	
  threshold)
	
  	
  	
  	
  directlySolve(problem)
	
  	
  else	
  {
	
  	
  	
  	
  do-­‐forked	
  {
	
  	
  	
  	
  	
  	
  	
  leftResult	
  	
  =	
  compute(left(problem))
	
  	
  	
  	
  	
  	
  	
  rightResult	
  =	
  compute(right(problem))
	
  	
  	
  	
  }
	
  	
  	
  	
  join(leftResult,	
  rightResult)
	
  	
  	
  	
  return	
  combine(leftResult,	
  rightResult)
	
  	
  }
}




                                                Keep overhead down:
                                                  sequential cutoff
ForkJoinPool
Implements ExecutorService
Autosize workers (overridable)
Work queue per worker
 Work-stealing between queues
ForkJoinPool
Work stealing
ForkJoinPool
    Work stealing




1
ForkJoinPool
    Work stealing




1
ForkJoinPool
    Work stealing




2

3

1
ForkJoinPool
              Work stealing




    st
      ol
         en

3               2
ForkJoinPool
    Work stealing




3     2
ForkJoinPool
    Work stealing




4     6

5     7

3     2
ForkJoinPool
    Work stealing



4




          sto
           len
5     7             6
ForkJoinPool
    Work stealing



4

8    10             12

          sto
           len
9    11             13

5     7             6
ForkJoinPool
Scalability
Patterns
          #1 Problem structure


Acyclic        CPU Bound




            - I/O upfront
            - No webcrawlers
              please...
Patterns
                         #2 Sequential cutoff


  Guidelines
                         compute(problem)	
  {
> 100 and < 10.000       	
  	
  if	
  (problem.size	
  <	
  threshold)
‘basic computational     	
  	
  	
  	
  directlySolve(problem)
                         	
  	
  else	
  {
steps’                   	
  	
  	
  	
  do-­‐forked	
  {
                         	
  	
  	
  	
  	
  	
  	
  ...
Experiment and tune      	
  	
  	
  	
  }
                         	
  	
  	
  	
  join	
  ...
                         	
  	
  }
Never lock/synchronize   }
Patterns
                         #3 Fork once, fool me twice



      Why?               left.fork()
                         rightResult	
  =	
  right.compute()
                         leftResult	
  =	
  left.join()
Implementation           return	
  leftResult	
  +	
  rightResult
specific
Avoids overhead
                         left.fork()
Especially on smallish   leftResult	
  =	
  left.join()
                         rightResult	
  =	
  right.compute()
tasks                    return	
  leftResult	
  +	
  rightResult
Patterns
                                            #4 Use convenience methods




invoke                                       invokeAll
fjTask.invoke();                             invokeAll(fjTask1,	
  fjTask2,
//	
  Equivalent	
  to                       	
  	
  	
  fjTaskN);
fjTask.fork();
fjTask.join();                               //	
  Or:
//	
  But	
  always	
  tries	
  execution
//	
  in	
  current	
  thread	
  first!      invokeAll(collectionOfTasks);
Demo


2.797.245 world cities (Maxmind.com)
Demo 1: simple search
Demo 2: lat/long bounded
Demo

Search range:
  i.e. 0.4°
ForkJoin & Java EE
   ForkJoinPool creates threads
    Illegal in EJBs
    CDI/Servlet is a gray area
   JCA/WorkManager could work
   @Asynchronous as alternative

But: Java EE7 may contain javax.util.concurrent
Comparison
                  ExecutorService

Thread pooling (bounded or
unbounded)
Single work queue (no workstealing)
Coarse-grained independent tasks
Blocking I/O ok
Comparison
                       MapReduce




Environment   Single JVM          Cluster

Model         Recursive forking   Often single map

Scales with   Cores/CPUs          Nodes

Worker        Workstealing        No inter-node
interaction                       communication
Criticism
Complex implementation
 (uses sun.misc.Unsafe)


                          Scalability > 100 cores?


         Questionable assumption:
           1-1 mapping worker
              thread to core
Criticism
Complex implementation
 (uses sun.misc.Unsafe)


                          Scalability > 100 cores?


         Questionable assumption:
           1-1 mapping worker
              thread to core


                                   Too low-level
Future
InfoQ: “What is supported out of the box?”



                         “Almost nothing".

             We chickened out; we are not going to release
                        the layers on top of this
           That means that right now, people who are using
            this framework are going to be the people who
                 actually get into this parallel recursive
                 decomposition and know how to use it.
Future
JDK 8 plans

   Parallel collections
     Depends on Project Lambda
   CountedCompleter for I/O



Some already available in jsr166extra
Future
int	
  findCities(List<String>	
  cities,	
  String	
  query)	
  {
	
  	
  	
  Pattern	
  p	
  =	
  Pattern.compile(query)
	
  	
  	
  return	
  cities.parallel()
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .filter(c	
  =>	
  p.matcher(c).matches());
	
  	
  	
  	
  
}




               int	
  findNearestCities(List<String>	
  lines,	
  int	
  lat,	
  int	
  lng)	
  {
               	
  	
  	
  return	
  lines.parallel()
               	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .map(c	
  =>	
  toCity(c))
               	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .filter(c	
  =>	
  c.isNear(lat,	
  lng))
               	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  .sort();
               }
Questions?


        Code @ bit.ly/bejug-fj

Más contenido relacionado

La actualidad más candente

The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Peter Antman
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyondFabio Tiriticco
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programmingEric Polerecky
 

La actualidad más candente (20)

The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 

Destacado

Jordan Brain Gain First Meeting in Amman Report
Jordan Brain Gain First Meeting in Amman ReportJordan Brain Gain First Meeting in Amman Report
Jordan Brain Gain First Meeting in Amman ReportBayan Waleed Shadaideh
 
Better Software Keynote The Complete Developer 07
Better Software Keynote  The Complete Developer 07Better Software Keynote  The Complete Developer 07
Better Software Keynote The Complete Developer 07Enthiosys Inc
 
Extend Your MS Dynamics ERP & CRM with a Complete BI Solution
Extend Your MS Dynamics ERP & CRM with a Complete BI SolutionExtend Your MS Dynamics ERP & CRM with a Complete BI Solution
Extend Your MS Dynamics ERP & CRM with a Complete BI Solutionwww.panorama.com
 
Enhance your microsoft bi stack to drive business user adoption slide share
Enhance your microsoft bi stack to drive business user adoption   slide shareEnhance your microsoft bi stack to drive business user adoption   slide share
Enhance your microsoft bi stack to drive business user adoption slide sharewww.panorama.com
 
02 the necto_application_ready
02 the necto_application_ready02 the necto_application_ready
02 the necto_application_readywww.panorama.com
 
Blogstarz Presentation Ter Baru
Blogstarz Presentation Ter BaruBlogstarz Presentation Ter Baru
Blogstarz Presentation Ter Barumusslizz
 
Proforma Branded Apps
Proforma Branded AppsProforma Branded Apps
Proforma Branded AppsJim Hanika
 
Lean startup Methodology
Lean startup MethodologyLean startup Methodology
Lean startup Methodologyali raza
 
Select Samples of Work
Select Samples of WorkSelect Samples of Work
Select Samples of Worklizzygreen
 
Four Pillars Zone
Four Pillars ZoneFour Pillars Zone
Four Pillars ZoneCarol Moxam
 
Pricing, Business Models, and What Things are Worth
Pricing, Business Models, and What Things are WorthPricing, Business Models, and What Things are Worth
Pricing, Business Models, and What Things are WorthEnthiosys Inc
 
Use BI to Beat the Competition
Use BI to Beat the CompetitionUse BI to Beat the Competition
Use BI to Beat the Competitionwww.panorama.com
 
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...Bayan Waleed Shadaideh
 
NL in Bo Pres Zadkine
NL in Bo Pres ZadkineNL in Bo Pres Zadkine
NL in Bo Pres Zadkineguest2c6f77b
 
Prism Capabilities Overview
Prism Capabilities OverviewPrism Capabilities Overview
Prism Capabilities Overviewseandbrady
 

Destacado (20)

Introduction àJava
Introduction àJavaIntroduction àJava
Introduction àJava
 
Unenclosable
UnenclosableUnenclosable
Unenclosable
 
Jordan Brain Gain First Meeting in Amman Report
Jordan Brain Gain First Meeting in Amman ReportJordan Brain Gain First Meeting in Amman Report
Jordan Brain Gain First Meeting in Amman Report
 
Better Software Keynote The Complete Developer 07
Better Software Keynote  The Complete Developer 07Better Software Keynote  The Complete Developer 07
Better Software Keynote The Complete Developer 07
 
Extend Your MS Dynamics ERP & CRM with a Complete BI Solution
Extend Your MS Dynamics ERP & CRM with a Complete BI SolutionExtend Your MS Dynamics ERP & CRM with a Complete BI Solution
Extend Your MS Dynamics ERP & CRM with a Complete BI Solution
 
Enhance your microsoft bi stack to drive business user adoption slide share
Enhance your microsoft bi stack to drive business user adoption   slide shareEnhance your microsoft bi stack to drive business user adoption   slide share
Enhance your microsoft bi stack to drive business user adoption slide share
 
AUX Cities
AUX CitiesAUX Cities
AUX Cities
 
自主性建築
自主性建築自主性建築
自主性建築
 
02 the necto_application_ready
02 the necto_application_ready02 the necto_application_ready
02 the necto_application_ready
 
Blogstarz Presentation Ter Baru
Blogstarz Presentation Ter BaruBlogstarz Presentation Ter Baru
Blogstarz Presentation Ter Baru
 
Proforma Branded Apps
Proforma Branded AppsProforma Branded Apps
Proforma Branded Apps
 
Lean startup Methodology
Lean startup MethodologyLean startup Methodology
Lean startup Methodology
 
Select Samples of Work
Select Samples of WorkSelect Samples of Work
Select Samples of Work
 
Four Pillars Zone
Four Pillars ZoneFour Pillars Zone
Four Pillars Zone
 
Pricing, Business Models, and What Things are Worth
Pricing, Business Models, and What Things are WorthPricing, Business Models, and What Things are Worth
Pricing, Business Models, and What Things are Worth
 
Content Strategy
Content StrategyContent Strategy
Content Strategy
 
Use BI to Beat the Competition
Use BI to Beat the CompetitionUse BI to Beat the Competition
Use BI to Beat the Competition
 
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...
Violating The Rights of The Child; When "Faith" Violates the Faith in Human R...
 
NL in Bo Pres Zadkine
NL in Bo Pres ZadkineNL in Bo Pres Zadkine
NL in Bo Pres Zadkine
 
Prism Capabilities Overview
Prism Capabilities OverviewPrism Capabilities Overview
Prism Capabilities Overview
 

Similar a Fork Join (BeJUG 2012)

Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)Igalia
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And BeyondMike Fogus
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
yield and return (poor English ver)
yield and return (poor English ver)yield and return (poor English ver)
yield and return (poor English ver)bleis tift
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMDierk König
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 

Similar a Fork Join (BeJUG 2012) (20)

F#3.0
F#3.0 F#3.0
F#3.0
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
Good news, everybody! Guile 2.2 performance notes (FOSDEM 2016)
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And Beyond
 
Why MacRuby Matters
Why MacRuby MattersWhy MacRuby Matters
Why MacRuby Matters
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
yield and return (poor English ver)
yield and return (poor English ver)yield and return (poor English ver)
yield and return (poor English ver)
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
 
User defined functions
User defined functionsUser defined functions
User defined functions
 

Más de Sander Mak (@Sander_Mak)

TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)Sander Mak (@Sander_Mak)
 
Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Sander Mak (@Sander_Mak)
 
Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Sander Mak (@Sander_Mak)
 

Más de Sander Mak (@Sander_Mak) (20)

Scalable Application Development @ Picnic
Scalable Application Development @ PicnicScalable Application Development @ Picnic
Scalable Application Development @ Picnic
 
Coding Your Way to Java 13
Coding Your Way to Java 13Coding Your Way to Java 13
Coding Your Way to Java 13
 
Coding Your Way to Java 12
Coding Your Way to Java 12Coding Your Way to Java 12
Coding Your Way to Java 12
 
Java Modularity: the Year After
Java Modularity: the Year AfterJava Modularity: the Year After
Java Modularity: the Year After
 
Desiging for Modularity with Java 9
Desiging for Modularity with Java 9Desiging for Modularity with Java 9
Desiging for Modularity with Java 9
 
Modules or microservices?
Modules or microservices?Modules or microservices?
Modules or microservices?
 
Migrating to Java 9 Modules
Migrating to Java 9 ModulesMigrating to Java 9 Modules
Migrating to Java 9 Modules
 
Java 9 Modularity in Action
Java 9 Modularity in ActionJava 9 Modularity in Action
Java 9 Modularity in Action
 
Java modularity: life after Java 9
Java modularity: life after Java 9Java modularity: life after Java 9
Java modularity: life after Java 9
 
Provisioning the IoT
Provisioning the IoTProvisioning the IoT
Provisioning the IoT
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)The Ultimate Dependency Manager Shootout (QCon NY 2014)
The Ultimate Dependency Manager Shootout (QCon NY 2014)
 
Modular JavaScript
Modular JavaScriptModular JavaScript
Modular JavaScript
 
Modularity in the Cloud
Modularity in the CloudModularity in the Cloud
Modularity in the Cloud
 
Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?Cross-Build Injection attacks: how safe is your Java build?
Cross-Build Injection attacks: how safe is your Java build?
 
Scala & Lift (JEEConf 2012)
Scala & Lift (JEEConf 2012)Scala & Lift (JEEConf 2012)
Scala & Lift (JEEConf 2012)
 
Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)
 
Akka (BeJUG)
Akka (BeJUG)Akka (BeJUG)
Akka (BeJUG)
 
Kscope11 recap
Kscope11 recapKscope11 recap
Kscope11 recap
 

Último

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Fork Join (BeJUG 2012)

  • 2. About Coding at ( ) Writing Blog @ branchandbound.net Speaking
  • 3. Agenda ForkJoin Setting the scene ForkJoin API & Patterns Comparisons & Future break Akka Introduction Actors Async IO
  • 9. Problem? So let the compiler/runtime solve it!
  • 10. Problem? So let the compiler/runtime solve it! n  <  2 n if  (n  <  2)    {  return  n;  } else    {  return  fib(n  -­‐  1)  +  fib(n  -­‐  2);  }
  • 11. Problem? So let the compiler/runtime solve it! Unfortunately not in , but feasible in pure functional languages like
  • 12. First attempt        public  static  int  fib(final  int  n)  {                if  (n  <  2)  {  return  n;  }                else  {                        final  int[]  t1  =  {0},  t2  =  {0};                                                Thread  thread1  =  new  Thread()  {                                public  void  run()  {                                        t1[0]  =  fib(n  -­‐  1);                                }  };                        Thread  thread2  =  new  Thread()  {                                public  void  run()  {                                                t2[0]  =  fib(n  -­‐  2);                                }  };                        thread1.start();  thread2.start();                        thread1.join();  thread2.join();                        return  t1[0]  +  t2[0];                }        } if  (n  <  2)    {  return  n;  } else    {  return  fib(n  -­‐  1)  +  fib(n  -­‐  2);  }
  • 13. Threads Threads are mostly waiting Improve with threadpooling but not by much starvation What if we sum in a new thread? synchronization visibility issues (Java Memory Model)
  • 14. ForkJoin Fork: Recursively decompose Result = 3 large task into subtasks Fib(4) Join: Fib(3) Fib(2) Await results of recursive tasks and combine Fib(2) Fib(1) Fib(1) Fib(0) Fib(1) Fib(0)
  • 15. ForkJoin Introducing: ForkJoinPool java.util.concurrent. java.util.concurrent.ForkJoinTask ForkJoinTask RecursiveAction RecursiveTask ForkJoinPool: void execute (ForkJoinTask<?>) T invoke (ForkJoinTask<T>)    
  • 16. ForkJoin compute(problem)  {    if  (problem.size  <  threshold)        directlySolve(problem)    else  {        do-­‐forked  {              leftResult    =  compute(left(problem))              rightResult  =  compute(right(problem))        }        join(leftResult,  rightResult)        return  combine(leftResult,  rightResult)    } } Keep overhead down: sequential cutoff
  • 17. ForkJoinPool Implements ExecutorService Autosize workers (overridable) Work queue per worker Work-stealing between queues
  • 19. ForkJoinPool Work stealing 1
  • 20. ForkJoinPool Work stealing 1
  • 21. ForkJoinPool Work stealing 2 3 1
  • 22. ForkJoinPool Work stealing st ol en 3 2
  • 23. ForkJoinPool Work stealing 3 2
  • 24. ForkJoinPool Work stealing 4 6 5 7 3 2
  • 25. ForkJoinPool Work stealing 4 sto len 5 7 6
  • 26. ForkJoinPool Work stealing 4 8 10 12 sto len 9 11 13 5 7 6
  • 28. Patterns #1 Problem structure Acyclic CPU Bound - I/O upfront - No webcrawlers please...
  • 29. Patterns #2 Sequential cutoff Guidelines compute(problem)  { > 100 and < 10.000    if  (problem.size  <  threshold) ‘basic computational        directlySolve(problem)    else  { steps’        do-­‐forked  {              ... Experiment and tune        }        join  ...    } Never lock/synchronize }
  • 30. Patterns #3 Fork once, fool me twice Why? left.fork() rightResult  =  right.compute() leftResult  =  left.join() Implementation return  leftResult  +  rightResult specific Avoids overhead left.fork() Especially on smallish leftResult  =  left.join() rightResult  =  right.compute() tasks return  leftResult  +  rightResult
  • 31. Patterns #4 Use convenience methods invoke invokeAll fjTask.invoke(); invokeAll(fjTask1,  fjTask2, //  Equivalent  to      fjTaskN); fjTask.fork(); fjTask.join(); //  Or: //  But  always  tries  execution //  in  current  thread  first! invokeAll(collectionOfTasks);
  • 32. Demo 2.797.245 world cities (Maxmind.com) Demo 1: simple search Demo 2: lat/long bounded
  • 33. Demo Search range: i.e. 0.4°
  • 34. ForkJoin & Java EE ForkJoinPool creates threads Illegal in EJBs CDI/Servlet is a gray area JCA/WorkManager could work @Asynchronous as alternative But: Java EE7 may contain javax.util.concurrent
  • 35. Comparison ExecutorService Thread pooling (bounded or unbounded) Single work queue (no workstealing) Coarse-grained independent tasks Blocking I/O ok
  • 36. Comparison MapReduce Environment Single JVM Cluster Model Recursive forking Often single map Scales with Cores/CPUs Nodes Worker Workstealing No inter-node interaction communication
  • 37. Criticism Complex implementation (uses sun.misc.Unsafe) Scalability > 100 cores? Questionable assumption: 1-1 mapping worker thread to core
  • 38. Criticism Complex implementation (uses sun.misc.Unsafe) Scalability > 100 cores? Questionable assumption: 1-1 mapping worker thread to core Too low-level
  • 39. Future InfoQ: “What is supported out of the box?” “Almost nothing". We chickened out; we are not going to release the layers on top of this That means that right now, people who are using this framework are going to be the people who actually get into this parallel recursive decomposition and know how to use it.
  • 40. Future JDK 8 plans Parallel collections Depends on Project Lambda CountedCompleter for I/O Some already available in jsr166extra
  • 41. Future int  findCities(List<String>  cities,  String  query)  {      Pattern  p  =  Pattern.compile(query)      return  cities.parallel()                                .filter(c  =>  p.matcher(c).matches());         } int  findNearestCities(List<String>  lines,  int  lat,  int  lng)  {      return  lines.parallel()                              .map(c  =>  toCity(c))                              .filter(c  =>  c.isNear(lat,  lng))                              .sort(); }
  • 42. Questions? Code @ bit.ly/bejug-fj