Java Reference
In-Depth Information
In this way, the
GameOfLifeAdvancer
instance is broken down into new
GameOfLifeAdvancer
instances that each processes only part of the Game of Life
board. Each instance waits for all the subordinate parts to be completed before return-
ing control to the caller. The resulting division of work can take advantage of the mul-
tiple CPUs available in the typical system today.
Tip
The
ForkJoinPool
is generally more efficient than an
ExecutorService
because it implements a work-stealing policy. Each thread has a
Queue
of work to
complete; if the
Queue
of any thread is empty, the thread will “steal” work from anoth-
er thread queue, making a more efficient use of CPU processing power.
10-11. Updating a Common Value Across
Multiple Threads
Problem
Your application needs to safely maintain a single summed value across multiple
threads.
Solution
Utilize a
DoubleAdder
or
LongAdder
to contain the value that is being summed
across multiple threads in order to ensure safe handling. In the following example, two
threads are adding values to a
DoubleAdder
at the same time, and in the end the
value is summed and displayed.
DoubleAdder da = new DoubleAdder();
private void start() {
Thread thread1 = new Thread(() -> {
for (int i1 = 0; i1 < 10; i1++) {
da.add(i1);
System.out.println("Adding " + i1);