Is Atomic Integer incrementAndGet() method thread safe? I don't see any use of synchronized keyword in it. I am using following code to generate the unique id:
public enum UniqueIdGenerator {
INSTANCE;
private AtomicLong instance = new AtomicLong(System.currentTimeMillis());
public long incrementAndGet() {
return instance.incrementAndGet();
}
}
I am wondering if multiple threads that would call the method to generate unique ID result in any issue.
UniqueIdGenerator.INSTANCE.incrementAndGet()
Thanks!
Yes, it is. It uses other, than synchronized, more efficient thread safety mechanism based on internal JDK class named Unsafe
Not only AtomicInteger
and AtomicLong
, atomic package classes are thread safe.
java.util.concurrent.atomic
A small toolkit of classes that support lock-free thread-safe programming on single variables.
In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
Instances of classes AtomicBoolean
, AtomicInteger
, AtomicLong
, and AtomicReference
each provide access and updates to a single variable of the corresponding type. Each class also provides appropriate utility methods for that type. For example, classes AtomicLong
and AtomicInteger
provide atomic increment methods.
YES! Its part of java.util.concurrent package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With