-1

I am reading the book "Core Java I" written by Cay S. Horstmann and at page 580 he mentiones about the LongAdder:

If you anticipate high contention [*1], you should simply use a LongAdder instead of an AtomicLong. The method names are slightly different. Call increment to increment a counter or add to add a quantity, and sum to retrieve the total.

var adder = new LongAdder();
for (. . .)
  pool.submit(() -> {
    while (. . .) {
       . . .
       if (. . .) adder.increment();
    }
});
. . .
long total = adder.sum();

Note Of course, the increment method does not return the old [*2] value. Doing that would undo the efficiency gain of splitting the sum into multiple summands.

In [*1] by the word "contention", I assume he means heavily overloaded second of the machine that there are lots of threads that runs the java code.

In [*2] he mentioned about the old value. What does old and new value in this context? Could you please explain briefly.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
tahasozgen2
  • 148
  • 1
  • 1
  • 9

2 Answers2

2

[*1]: The term "contention" in context of multithreading means that many threads try to access/call/update something at the same time; in this case the LongAdder or counter in general.

[*2]: The old value in this context is the previous value of the LongAdder. While all updating methods of AtomicLong, except set and some CAS-methods, return the previous value stored, LongAdder#increment returns void. The new value is simply the .. new value, the one that you can get via sum.

The class LongAdder works differently than AtomicLong to increase throughput, which is why e.g. increment doesn't return anything. You can read about it here: How LongAdder performs better than AtomicLong

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
2

LongAdder doesn't maintain one value. When you increment/add a new value, it stores 1 or new value in different Cell. It doesn't maintain total value.

When you want to get actual value you call sum() method which sums all values to get you result.

For better understanding, here's how the sum method is implemented in LongAdder:

 public long sum() {
        Cell[] cs = cells;
        long sum = base;
        if (cs != null) {
            for (Cell c : cs)
                if (c != null)
                    sum += c.value;
        }
        return sum;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
the Hutt
  • 16,980
  • 2
  • 14
  • 44