Java Reference
In-Depth Information
10-10. Breaking Down Tasks into Dis-
crete Units of Work
Problem
You have an algorithm that benefits from using a divide-and-conquer strategy , which
refers to the ability of breaking down a unit of work into two separate subunits and
then piecing together the results from these subunits. The subunits can then be broken
down into more subunits of work until reaching a point where the work is small enough
to just be executed. By breaking down the unit of work into subunits, you can take ad-
vantage of the multicore nature of today's processors with minimum pain.
Solution
The new Fork / Join framework makes applying the divide-and-conquer strategy
straightforward. The following example creates a representation of the Game of Life.
The code uses the Fork / Join framework to speed up the calculation for each itera-
tion when advancing from one generation to the next:
////////////////////////////////////////////////////////////////
ForkJoinPool pool = new ForkJoinPool();
long i = 0;
while (shouldRun) {
i++;
final boolean[][] newBoard = new
boolean[lifeBoard.length][lifeBoard[0].length];
long startTime = System.nanoTime();
GameOfLifeAdvancer advancer = new
GameOfLifeAdvancer(lifeBoard, 0,0, lifeBoard.length-1,
lifeBoard[0].length-1,newBoard);
pool.invoke(advancer);
long endTime = System.nanoTime();
if (i % 100 == 0 ) {
System.out.println("Taking
Search WWH ::




Custom Search