Adders and accumulators

Following the Java API documentation, in cases of multithreading applications that update frequently but read less frequently, it is recommended to rely on LongAdder, DoubleAdder, LongAccumulator, and DoubleAccumulator, instead of the AtomicFoo classes. For such scenarios, these classes are designed to optimize the usage of threads.

This means that, instead of using AtomicInteger for counting the integers from 1 to 1,000,000, we can use LongAdder as follows:

public class AtomicAdder implements Runnable {

public static LongAdder count = new LongAdder();

@Override
public void run() {

count.add(1);
}

public long getCount() {

return count.sum();
}
}

Alternatively, we can use LongAccumulator as follows:

public class AtomicAccumulator implements Runnable {

public static LongAccumulator count
= new LongAccumulator(Long::sum, 0);

@Override
public void run() {

count.accumulate(1);
}

public long getCount() {

return count.get();
}
}

The LongAdder and DoubleAdder are right for scenarios that imply additions (operations specific to additions), while LongAccumulator and DoubleAccumulator are right for scenarios that rely on a given function to combine values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.144.194