Home  >  Core Java

Example of AtomicMarkableReference in Java

By Arvind Rai, December 25, 2012
1. AtomicMarkableReference belongs to the package java.util.concurrent.atomic.
2. AtomicMarkableReference is available from jdk1.5.
3. The object of AtomicMarkableReference is created with one reference and one boolean mark.
4. AtomicMarkableReference has the methods attemptMark. This method sets the mark if expected value matches the current value.
5. compareAndSet method sets the value of both reference and mark before checking the current values first.
6. set method sets the reference and Boolean mark without checking any condition.
package com.concretepage;

import java.util.concurrent.atomic.AtomicMarkableReference;

public class AtomicMarkableReferenceTest {
	AtomicMarkableReference<String> amr= new AtomicMarkableReference<String>("ref",false);
	
	class AddThread implements Runnable{

		@Override
		public void run() {
		//update the value of mark as true if "ref" matches to current reference
		amr.attemptMark("ref",true);
		
		//if current reference is "ref" and current mark is "true" then it change as newref and false respectivelly
		amr.compareAndSet("ref","newref",true,false);
		
		// sets the new refernce and new mark without any check  
		amr.set("reference",true);
		}
		
	}
	
   public static void main(String... args){
	   new Thread(new AtomicMarkableReferenceTest().new AddThread()).start();
	   new Thread(new AtomicMarkableReferenceTest().new AddThread()).start();
   }

}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us