Skip to content

Atomic Objects

Vishnu Garg edited this page Aug 3, 2018 · 2 revisions

Atomic Objects

AtomicBoolean

he AtomicBoolean class provides you with a boolean variable which can be read and written atomically, and which also contains advanced atomic operations like compareAndSet(). The AtomicBoolean class is located in the java.util.concurrent.atomic package.

1. Operations

//Creations
AtomicBoolean atomicBoolean = new AtomicBoolean();
AtomicBoolean atomicBoolean1 = new AtomicBoolean(true);
//Get
boolean value = atomicBoolean.get();
//Set
atomicBoolean.set(false);
//Swapping the AtomicBoolean's Value
boolean oldValue = atomicBoolean.getAndSet(false);
// Compare and set
boolean wasNewValueSet = atomicBoolean.compareAndSet(
    expectedValue, newValue);

AtomicInteger

The AtomicInteger class provides you with a int variable which can be read and written atomically, and which also contains advanced atomic operations like compareAndSet(). The AtomicInteger class is located in the java.util.concurrent.atomic package, 1. Operations

//Creation
AtomicInteger atomicInteger = new AtomicInteger();
AtomicInteger atomicInteger1 = new AtomicInteger(123);
//Get
int theValue = atomicInteger.get();
//Set
atomicInteger.set(234);
//
atomicInteger.compareAndSet(expectedValue, newValue);

addAndGet(10);
getAndAdd(10);
getAndIncrement();
incrementAndGet();
decrementAndGet();
getAndDecrement();
Clone this wiki locally