view src/treecms/tree/util/LockableReference.java @ 24:68021f7091e1

commit
author shoshi
date Sun, 12 Jun 2011 20:41:20 +0900
parents 77a894c0b919
children
line wrap: on
line source

package treecms.tree.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

public class LockableReference<V> 
{
	public static void main(String _args[]) throws InterruptedException
	{
		//test code for LockableReference<V>
		
		Integer i = new Integer(10);
		final LockableReference<Integer> ref = new LockableReference<Integer>(i);
		
		Runnable r = new Runnable(){
			@Override
			public void run()
			{
				String name = Thread.currentThread().getName();
				System.out.println(name + ": acquire lock");
				ref.lock();
				System.out.println(name + ": locked");
				System.out.println(name + ": ref is " + ref.get());
				ref.put(2);
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				try {
					br.readLine();
				}catch(IOException _e){
					_e.printStackTrace();
				}
				ref.unlock();
			}
		};
		
		Thread th1 = new Thread(r);
		Thread th2 = new Thread(r);
		
		th1.start();
		th2.start();
		
		th1.join();
		th2.join();
	}
	
	private final AtomicReference<V> m_ref;
	private final ReentrantLock m_lock;
	
	public LockableReference(V _ref)
	{
		m_ref = new AtomicReference<V>(_ref);
		m_lock = new ReentrantLock(true);
	}
	
	public V get()
	{
		V ret;
		m_lock.lock();
		ret = m_ref.get();
		m_lock.unlock();
		return ret;
	}
	
	public boolean isLocked()
	{
		return m_lock.isLocked();
	}
	
	public void put(V _ref)
	{
		m_lock.lock();
		m_ref.set(_ref);
		m_lock.unlock();
	}
	
	public void lock()
	{
		m_lock.lock();
	}
	
	public void unlock()
	{
		m_lock.unlock();
	}
}