javamultithreadingatomicinteger

Is Atomic Integer incrementAndGet() thread safe?


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!


Solution

  • Yes, it is. It uses other, than synchronized, more efficient thread safety mechanism based on internal JDK class named Unsafe