问题
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 wandering if multiple threads that would call the method to generate unique ID would result in any issue?
UniqueIdGenerator.INSTANCE.incrementAndGet()
Thanks!
回答1:
Yes, it is. It uses other, than synchronized, more efficient thread safety mechanism based on internal ask class named Unsafe
回答2:
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.
回答3:
YES! Its part of java.util.concurrent package.
回答4:
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.
来源:https://stackoverflow.com/questions/44053300/is-atomic-integer-incrementandget-thread-safe