top of page

Subscribe to Wisdom

Thanks for Subscribing!

Writer's picturePuru Uttam

Atomic Variables

In multithreading environment, a shared entity which can be object or variable can lead to inconsistency as many threads will be concurrently accessing this object and performing operations such as updation of the object value. Then this will lead to corrupt data in the program or database. So when we need to access shared object among multiple threads, data should be consistent with the right values. Here we can use Atomic Variables.


There are various Atomic Classes present in Java such as AtomicInteger, AtomicBoolean, AtomicLong and AtomicReference which provided us the atomic variables for int, boolean, long and object reference.


It is only applicable to the variables and it is efficient in concurrent environment (high performance).


Non-blocking algorithms can be implemented using Atomic variables.


There are some methods provided by these classes :

  • set(int value) : Set the value

  • get() : get the value

  • lazySet(int value) : set the given value eventually

  • compareAndSet(int previous, int updated) : if current value matches the previous expected value then it updates it atomically

  • incrementAndGet(int value) : always increases the current value by 1 value

  • decrementAndGet() : decrements the current value by 1



//Atomic Variable Declaration
private AtomicInteger value= new AtomicInteger();


import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounterExample {
    private AtomicInteger value = new AtomicInteger(0);

    public void increment() {
        value.incrementAndGet();
    }

    public void decrement() {
        value.decrementAndGet();
    }

    public int getValue() {
        return value.get();
    }

}


In this quick wisdom, an alternate way of handling concurrency is described where disadvantages of locking can be avoided mainly deadlocks and livelocks.

7 views0 comments

Recent Posts

See All

Comments


Modern Digital Watch
bottom of page