Skip to content

Instantly share code, notes, and snippets.

@nephilim
Created April 5, 2011 02:13
Show Gist options
  • Save nephilim/902900 to your computer and use it in GitHub Desktop.
Save nephilim/902900 to your computer and use it in GitHub Desktop.
concurrency - ReadWriteLock
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import junit.framework.TestCase;
public class BasicConcurrentTest extends TestCase {
public void testReadWriteLock() throws Exception {
final Counter c = new Counter();
Thread write1 = new Thread() {
@Override
public void run() {
c.increment();
}
};
Thread write2 = new Thread() {
@Override
public void run() {
c.increment();
}
};
Thread read1 = new Thread() {
@Override
public void run() {
int current = c.current();
System.out.println(current);
}
};
Thread read2 = new Thread() {
@Override
public void run() {
int current = c.current();
System.out.println(current);
}
};
write1.start();
write2.start();
read1.start();
read2.start();
System.out.println("");
}
class Counter {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private int value =0;
/**
* WriteLock은
* 1) ReadLock이 걸린 경우 대기한다
* 2) 다른 WriteLock이 걸린 경우에도 대기한다.
* @return
*/
public int increment() {
lock.writeLock().lock();
try {
++value;
return value;
} finally {
lock.writeLock().unlock();
}
}
/**
* ReadLock은
* 1) WriteLock이 걸린 경우 대기한다.
* 2) 다른 ReadLock에는 영향을 받지 않는다.
*
* @return
*/
public int current() {
lock.readLock().lock();
try{
return value;
} finally {
lock.readLock().unlock();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment