Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the LongAdder a wrong choice for the ID generator?

Tags:

java

java-8

Java's LongAdder is more performant then AtomicLong. However, if I am getting this correctly, it is not a good choice for the ID generator, because there is no atomic 'read-and-increment' operation.

I am asking this because I see people recommend it for the ID generation, and I do not see the point since the sum() will be called for every operation.

Is the LongAdder a good or bad choice for the simple long ID generator?

like image 977
igr Avatar asked Jun 07 '18 10:06

igr


2 Answers

I think you have already answered your own question. It is definitely overkill for id generation from single thread and is not usable in multi-threaded scenario because there is no atomic incrementAndGet like operation. So the answer has to be it is not a good choice.

As javadoc says this class is useful for things like collecting statistics and such where contention is potentially high:

This class is usually preferable to AtomicLong when multiple threads update a common sum that is used for purposes such as collecting statistics, not for fine-grained synchronization control.

like image 64
hgrey Avatar answered Nov 19 '22 11:11

hgrey


First is that Java's LongAdder is more performant then AtomicLong is not very correct either. It is the case if there is high contention over it - otherwise it's just the same as AtomicLong internally. But even so - you should be aware that it uses some extra space so that each Thread computes the result separately, so when sum is called it just gathers those results.

But definitely not a good choice for an ID generator, either way.

like image 27
Eugene Avatar answered Nov 19 '22 12:11

Eugene