AtomicInteger

What can AtomicInteger do for you?

The AtomicInteger class provides you with a int variable which can be read and written actomically.You can create an AtomicInteger with the initial value 0 like this:

AtomicInteger atomicInteger = new AtomicInteger();

If you want to create an AtomicInteger with an initial value,you can do so like this:

AtomicInteger atomicInteger = new AtomicInteger(123);

Set() method

You can set the value of an AtomicInteger instance via the set() method:

atomicInteger.set(235);

compareAndSet() method

The AtomicIngeter class also has an atomic compareAndSet() method.For example:

AtomicInteger atomicInteger = new AtomicInteger(123);
int expectedValue = 123;
int newValue = 555;
atomicInteger.compareAndSet(expectedValue,newValue);

This example first creates an AtomicInteger instance with an initial value of 123.Then it compares the value of the atomicInteger to expectedValue and if they are equal ,the new value of the atomicInteger becomes 555.

Other methods to add a value to the AtomicInteger

  • addAndSet():adds a number to the AtomicInteger and returns its value after the addition.
  • getAndAdd():adds a number to the AtomicInteger but returns the value the AtomicInteger had before the value was added.
  • getAndIncrement(): adds 1 to the value of the AtomicInteger,inside the method,it returnsgetAndAddInt(this,VALUE,1)
  • incrementAndGet():adds 1 to the value of the AtomicInteger,inside the method,it returnsgetAndAddInt(this,VALUE,1)+1

Subtracting from the AtomicInteger Value

The AtomicInteger class also contains a few methods for subtracting values from the AtomicInteger value atomically.

  • decrementAndGet():It actually returns"getAndAddInt(this,VALUE,-1) -1"
  • getAndDecrement():It actually returns"getAndAddInt(this,VALUE,-1)"

Most of the developers know the benefits of threads(responsiveness,exploiting,multicores,etc),most of them also know the risks of threads(data inconsistency,deadlock,context switch overhead,etc).

Thread synchronization is needed when multiple threads access some changeable data and one of them might change it.

Synchronization provided in java enables us to enforce two things:atomicity and visibility.

When you want to change an Integer variable between threads,beside using synchronized key word,you can use AtomicIngeter class to achieve it.