Home  >  Core Java

Example of AtomicInteger in Java

By Arvind Rai, December 25, 2012
1. AtomicInteger belongs to the package java.util.concurrent.atomic and is available in java from jdk1.5.
2. AtomicInteger will be updated atomically means it will be thread safe.
3. It behaves like volatile variables.
4. AtomicInteger is used where we want to increment and subtract values from a variable atomically.
package com.concretepage;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest{
	AtomicInteger ai= new AtomicInteger(10);
	class AddThread implements Runnable{

		@Override
		public void run() {
		//ads the 5 in current value
		ai.addAndGet(5);
		
		//current value is 15, then 5 is added to current value
		ai.compareAndSet(15,5);
		
			System.out.println(ai.get());
		}
		
	}
	
	class SubThread implements Runnable{

		@Override
		public void run() {
			
			//decrements by 1 from current value 
			ai.decrementAndGet();
			
			//weakly compare the first args to current value and sets
			ai.weakCompareAndSet(10,20);
			System.out.println(ai.get());
		}
		
	}
	
   public static void main(String... args){
	   new Thread(new AtomicIntegerTest().new AddThread()).start();
	   new Thread(new AtomicIntegerTest().new SubThread()).start();
   }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us