We would like to know how to use ReadWriteLock on Variable.
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; //from w w w .ja v a2 s. com abstract class ThreadSafeWrapper<T> { ReadWriteLock lock = new ReentrantReadWriteLock(); T object; public ThreadSafeWrapper(T object) { this.object = object; } public final void methodOneWriteLock(String var) { lock.writeLock().lock(); try { doMethodOne(object, var); } finally { lock.writeLock().unlock(); } } public final void methodTwoReadLock(String var) { lock.readLock().lock(); try { doMethodTwo(object, var); } finally { lock.readLock().unlock(); } } abstract void doMethodOne(T obj, String var); abstract void doMethodTwo(T obj, String var); } public class Main { public static void main(String[] args) { ThreadSafeWrapper<String> wrapper = new ThreadSafeWrapper<String>("lala") { @Override protected void doMethodOne(String obj, String var) { System.out.println("method one: " + obj + " " + var); } @Override protected void doMethodTwo(String obj, String var) { System.out.println("method two: " + obj + " " + var); } }; wrapper.methodOneWriteLock("foo"); wrapper.methodTwoReadLock("bar"); } }
The code above generates the following result.