Counting under high concurrency - LongAdder


1. What is LongAdder

When counting under high concurrency, AtomicLong/AtomicInt should be the first thing that comes to mind. AtomicXX can guarantee the accuracy of counting under concurrency, and internally uses CAS to solve the problem of concurrency security. When a large number of threads update a variable at the same time, only one thread can succeed at any point in time, and most threads will try again by spinning after the update attempt fails, which seriously occupies the CPU time slice. This can lead to system performance issues.

LongAdder adopts a segmentation method to reduce the probability of concurrency conflicts by maintaining a base value base and Cell array. It can be used in application scenarios such as the number of likes for hot comments.


2. Working principle

The basic idea of ​​LongAdder is to disperse hotspots, disperse the value value into a Cell array, different threads will hit different slots of the array, and each thread only performs CAS operation on the value in its own slot, so the hotspots are dispersed. The probability of conflict is much smaller. If you want to get the real long value, just accumulate the variable values ​​in each slot and return. sum() will accumulate the value and base in all Cell arrays as the return value.

LongAdder does not create a Cell array at the beginning, it also maintains a base value, and only creates or expands when the CAS update fails.

In the case of no competition, LongAdder operates on the same base as AtomicLong and directly adds to the variable base.

When there is a competition relationship, changing space for time means splitting a value into a Cell array. When multiple threads need to operate on the value at the same time, you can hash the thread ID to get the hash value, and then map to a subscript of the array cells according to the hash value, and then perform an auto-increment operation on the value corresponding to the subscript. When all the threads have finished their operations, add up all the values ​​of the array cells and the uncompetitive value base as the final result.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44153131/article/details/129827113