Java Reference
In-Depth Information
Note ThreadLocalRandom leverages thread-local variables, which I discussed
in Chapter 4 's coverage of Java's Threading API.
Fork/Join Framework
Thereisalwaysaneedforcodetoexecutefaster.Historically,thisneedwasaddressed
by increasing microprocessor speeds and/or by supporting multiple processors.
However,somewherearound2003,microprocessorspeedsstoppedincreasingbecause
of natural limits. To compensate, processor manufacturers started to add multiple pro-
cessing cores to their processors, to increase speed through massive parallelism.
Note Parallelism referstorunningthreads/taskssimultaneouslythroughsomecom-
binationofmultipleprocessorsandcores.Incontrast, concurrency isamoregeneral-
izedformofparallelisminwhichthreadsrunsimultaneouslyorappeartorunsimultan-
eouslythroughtaskswitching,alsoknownas virtual parallelism .Somepeoplefurther
characterizeconcurrencyasapropertyofaprogramoroperatingsystemandparallel-
ism as the run-time behavior of executing multiple tasks simultaneously.
Java supports concurrency via the Threading API and concurrency utilities such as
threadpools.Theproblemwithconcurrencyisthatitdoesn'tmaximizetheuseofavail-
able processor/core resources. For example, suppose you have created a sorting al-
gorithmthatdividesanarrayintotwohalves,assignstwothreadstosorteachhalf,and
merges the results after both threads finish.
Let'sassumethateachthreadrunsonadifferentprocessor.Becausedifferentamounts
of element reordering may occur in each half of the array, it's possible that one thread
will finish before the other thread and must wait before the merge can happen. In this
case, a processor resource is wasted.
Thisproblem(andtherelatedproblemsofthecodebeingverboseandhardertoread)
canbesolvedbyrecursivelybreakingataskintosubtasksandcombiningresults.These
subtasksruninparallelandcompleteapproximatelyatthesametime(ifnotatthesame
moment),wheretheirresultsaremergedandpassedupthestacktothepreviouslayerof
subtasks.Hardlyanyprocessortimeiswastedthroughwaiting,andtherecursivecodeis
lessverboseand(usually)easiertounderstand.JavaprovidestheFork/JoinFramework
to implement this scenario.
Fork/Joinconsistsofaspecialexecutorserviceandthreadpool.Theexecutorservice
makesataskavailabletotheframework,andthistaskisbrokendownintosmallertasks
that are forked (executed by different threads) from the pool. A task waits until joined
(its subtasks finish).
Search WWH ::




Custom Search