5

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!

Abhi
  • 314
  • 1
  • 7
  • 23
Aman
  • 1,170
  • 3
  • 15
  • 29
  • 1
    Yes it is. And `AtomicLong` is too. – Elliott Frisch May 18 '17 at 16:32
  • 2
    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html. This is linked from the first sentence of AtomicInteger's javadoc. And it says: *A small toolkit of classes that support lock-free thread-safe programming on single variables* – JB Nizet May 18 '17 at 16:32
  • 2
    Not only is it thread-safe, but in fact its thread-safety is the only reason to use it (as opposed to a plain `int`). – yshavit May 18 '17 at 16:37

4 Answers4

6

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

jwj
  • 528
  • 3
  • 13
AlexR
  • 114,158
  • 16
  • 130
  • 208
5

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.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
1

YES! Its part of java.util.concurrent package.

Minh Kieu
  • 475
  • 3
  • 9
1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523