Home  >  Core Java

Example of AtomicReferenceArray in Java

By Arvind Rai, December 26, 2012
1. AtomicReferenceArray belongs to the package java.util.concurrent.atomic. It is available from jdk1.5.
2. java.util.concurrent.atomic is thread safe.
3. In AtomicReferenceArray , elements can be updated atomitically. It has methods like weakCompareAndSet and compareAndSet.
4. AtomicReferenceArray can be created with given size or directly an array can be passed.
package com.concretepage;

import java.util.concurrent.atomic.AtomicReferenceArray;

public class AtomicReferenceArrayTest {
	AtomicReferenceArray<String> ara= new AtomicReferenceArray<String>(10);
	
	class AddThread implements Runnable{

		@Override
		public void run() {
			
		//sets value at the index 1
		ara.set(0,"ref");
		
		//at index 0, if current reference is "ref" then it changes as newref 
		ara.compareAndSet(0,"ref","newref");
		
		//at index 0, if current value is newref, then it is sets as finalref
		ara.weakCompareAndSet(0,"newref","finalref");
		
		System.out.println(ara.get(0));
		
		}
		
	}
	
   public static void main(String... args){
	   new Thread(new AtomicReferenceArrayTest().new AddThread()).start();
	   new Thread(new AtomicReferenceArrayTest().new AddThread()).start();
   }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us