Home  >  Core Java

Example of AtomicReference in Java

By Arvind Rai, December 25, 2012
1. AtomicReference belongs to the package java.util.concurrent.atomic.
2. AtomicReference is available from jdk1.5.
3. The object of AtomicReference is created with one reference.
4. compareAndSet> method sets the value of reference checking the current values first.
5. set method sets the reference without checking any condition.
package com.concretepage;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceTest {
	AtomicReference<String> ar= new AtomicReference<String>("ref");
	
	class AddThread implements Runnable{

		@Override
		public void run() {
			
		//if current reference is "ref" then it changes as newref 
		ar.compareAndSet("ref","newref");
		
		// sets the new reference without any check  
		ar.set("reference");
		
		//sets new value and return the old value
		String s= ar.getAndSet("reference1");
		
		System.out.println(s);
		
		}
	}
	
        public static void main(String... args){
	        new Thread(new AtomicReferenceTest().new AddThread()).start();
	        new Thread(new AtomicReferenceTest().new AddThread()).start();
        }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us