Atomicinteger in java?

M.hosein abbasi
2 min readDec 11, 2021

--

AtomicInteger is used in multithreaded environments when you need to make sure that only one thread can update an int variable. The advantage is that no external synchronization is required since the operations which modify its value are executed in a thread-safe way.

Following is the list of important methods available in the AtomicInteger class.

accumulateAndGet(int x, IntBinaryOperator accumulatorFunction)

Atomically updates the current value with the results of applying the given function to the current and given values, returning the updated value.

addAndGet(int delta)

Atomically adds the given value to the current value.

compareAndSet(int expect, int update)

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

decrementAndGet()

Atomically decrements by one the current value.

doubleValue()

Returns the value of this AtomicInteger as a double after a widening primitive conversion.

floatValue()

Returns the value of this AtomicInteger as a float after a widening primitive conversion.

get()

Gets the current value.

getAndAccumulate(int x, IntBinaryOperator accumulatorFunction)

Atomically updates the current value with the results of applying the given function to the current and given values, returning the previous value.

getAndAdd(int delta)

Atomically adds the given value to the current value.

getAndDecrement()

Atomically decrements by one the current value.

getAndIncrement()

Atomically increments by one the current value.

getAndSet(int newValue)

Atomically sets to the given value and returns the old value.

getAndUpdate(IntUnaryOperator updateFunction)

Atomically updates the current value with the results of applying the given function, returning the previous value.

incrementAndGet()

Atomically increments by one the current value.

intValue()

Returns the value of this AtomicInteger as an int.

lazySet(int newValue)

Eventually sets to the given value.

longValue()

Returns the value of this AtomicInteger as a long after a widening primitive conversion.

set(int newValue)

Sets to the given value.

toString()

Returns the String representation of the current value.

updateAndGet(IntUnaryOperator updateFunction)

Atomically updates the current value with the results of applying the given function, returning the updated value.

weakCompareAndSet(int expect, int update)

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

I hope it was useful for you.

Source : docs.oracle.com

--

--