Example of AtomicLong in Java
December 25, 2012
1. AtomicLong belongs to the package java.util.concurrent.atomic and is available in java from jdk1.5.
2. AtomicLong will be updated atomically means it will be thread safe.
3. AtomicLong is used where we want to increment and subtract values from a variable atomically.
4. AtomicLong does not deal with those classes which are number based because AtomicLong dos not extend Number.
package com.concretepage; import java.util.concurrent.atomic.AtomicLong; public class AtomicLongTest { AtomicLong al= new AtomicLong(10); class AddThread implements Runnable{ @Override public void run() { //ads the 5 in current value al.addAndGet(5); //current value is 15, then 5 is added to current value al.compareAndSet(15,5); System.out.println(al.get()); } } class SubThread implements Runnable{ @Override public void run() { //decrements by 1 from current value al.decrementAndGet(); //weakly compare the first args to current value and sets al.weakCompareAndSet(10,20); System.out.println(al.get()); } } public static void main(String... args){ new Thread(new AtomicLongTest().new AddThread()).start(); new Thread(new AtomicLongTest().new SubThread()).start(); } }