Home  >  Core Java

Example of AtomicLongArray in Java

By Arvind Rai, December 25, 2012
1. AtomicLongArray belongs to the package java.util.concurrent.atomic.
2. java.util.concurrent.atomic is an array of integer.
3. AtomicLongArray is thread- safe. The values of AtomicLongArray can be modified automatically in multi threaded environment.
4. AtomicLongArray is available in java from jdk1.5.
package com.concretepage;

import java.util.concurrent.atomic.AtomicLongArray;

public class AtomicLongArrayTest {
	AtomicLongArray ala= new AtomicLongArray (10);
	class AddThread implements Runnable{

		@Override
		public void run() {
		//add the value 2 at index 1 
		ala.addAndGet(1,15);
		
		//at index 0, if current value is 15, then 5 is added to current value
		ala.compareAndSet(1,15,5);
		
			System.out.println(ala.get(1));
		}
		
	}
	
	class SubThread implements Runnable{

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






©2019 concretepage.com | Privacy Policy | Contact Us