Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Atomic Variable set() vs compareAndSet()

I want to know the difference between set() and compareAndSet() in atomic classes. Does the set() method also ensure the atomic process? For example this code:

public class sampleAtomic{
    private static AtomicLong id = new AtomicLong(0);

    public void setWithSet(long newValue){
        id.set(newValue);
    }

    public void setWithCompareAndSet(long newValue){
        long oldVal;
        do{
            oldVal = id.get();
        }
        while(!id.compareAndGet(oldVal,newValue)
    }
}

Are the two methods identical?

like image 972
Chrisma Andhika Avatar asked Oct 08 '13 03:10

Chrisma Andhika


People also ask

Is compareAndSet atomic?

compareAndSet. Atomically sets the value to the given updated value if the current value == the expected value.

What is atomic variable in Java?

Atomic is a toolkit of variable java. util. concurrent. atomic package classes, which assist in writing lock and wait-free algorithms with the Java language. An algorithm requiring only partial threads for constant progress is lock-free.

What is AtomicInteger and when to use?

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

How does AtomicInteger work in Java?

AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.


1 Answers

The set and compareAndSet methods act differently:

  • compareAndSet : Atomically sets the value to the given updated value if the current value is equal (==) to the expected value.
  • set : Sets to the given value.

Does the set() method also ensure the atomic process?

Yes. It is atomic. Because there is only one operation involved to set the new value. Below is the source code of the set method:

public final void set(long newValue) {
        value = newValue;
}
like image 120
Debojit Saikia Avatar answered Oct 23 '22 23:10

Debojit Saikia