Reputation: 1240
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!
Upvotes: 5
Views: 10735
Reputation: 115418
Yes, it is. It uses other, than synchronized, more efficient thread safety mechanism based on internal JDK class named Unsafe
Upvotes: 6
Reputation: 38950
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.
Upvotes: 5
Reputation: 727137
Yes. In fact, this is one of the stated goals of implementing AtomicLong
:
An
AtomicLong
is used in applications such as atomically incremented sequence numbers
Each of the multiple threads accessing incrementAndGet
concurrently will get a unique number.
Upvotes: 1