Java code example: simple singleton lock using with Atomic variables

I needed a very simple lock system for a software demo for operation on HashMap, instead of using ReentrantLock from java.util.concurrent.locks i chose to use Atomic classes from java.util.concurrent.atomic.* .

My demo has a very LONG blocking thread that writes on a shared HashMap, the following class permits me to tune the sleep time for the lock without using a syncronized queue.

Using AtomicInteger in place of AtomicBoolean gives the possibility to use multi-level lock levels

package com.simonecaruso;
 
import java.util.concurrent.atomic.AtomicInteger;
 
public class ConfigLock {
 
	static ConfigLock uniq  = null;
	static AtomicInteger i = 0;
 
	public static synchronized ConfigLock getInstance(){
		if(uniq == null)
			uniq = new ConfigLock();
		return uniq;
	}
 
	public static boolean isLocked(){
		return i.intValue() > 0 ? true : false;
	}
 
	public static boolean tryLock(){
		return i.compareAndSet(0, 1);
	}
 
	public static boolean unLock(){
		return i.compareAndSet(1, 0);
	}
 
	public static boolean lock() throws InterruptedException{
		while(i.compareAndSet(0, 1) != true)
			Thread.sleep(100);
		return true;
	}
}
Share

One Reply to “Java code example: simple singleton lock using with Atomic variables”

  1. Hello admin, i found this post on 20 spot in google’s search results.

    You should reduce your bounce rate in order to rank in google.

    This is major ranking factor nowadays. There is very handy
    wordpress plugin which can help you. Just search in google for:

    Lilas’s Bounce Plugin

Leave a Reply

Your email address will not be published. Required fields are marked *