Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 299
Aman Avatar asked May 18 '17 16:05

Aman


3 Answers

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

like image 50
AlexR Avatar answered Sep 22 '22 06:09

AlexR


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.

like image 31
Ravindra babu Avatar answered Sep 20 '22 06:09

Ravindra babu


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

like image 42
Minh Kieu Avatar answered Sep 20 '22 06:09

Minh Kieu