general java
[Guava] Monitor 예제
'김용환'
2015. 4. 21. 08:33
Guava의 Monitor 클래스에 대한 API를 보면 기존의 locking에 대한 좋은 내용이 나온다.
synchronized(notifyAll, wait)와 ReentrantLock(signal, Condition)에 대한 설명이 있다.
Guava의 Monitor 예제는 위에서 언급한 synchronized와 ReentrantLock개념을 잘 섞어놓았다. 이해하기 쉽고 직감적이다.
자바 처음 공부할 때는 아래 구문을 만났을 때, 특이하다고 생각했다.
jvm 관점이야. 아래 while 문이 특이하다고 생각했다.
while(조건문) {
awit();
}
Guava의 Monitor의 개념은 좀 명확한 개념이 있다.
monitor.enter()
try {
do_something();
} finally {
monitor.leave();
}
if (monitor.enterIf(guard)) {
try {
do_something();
} finally {
monitor.leave();
}
} else {
do_anotherthing_without_monitor();
}
예제
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Monitor;
public class GuavaTest {
List<String> list = Lists.newArrayList();
Monitor monitor = new Monitor();
Monitor.Guard capacityGuard = new Monitor.Guard(monitor) {
@Override
public boolean isSatisfied() {
return (list.size() < 1);
}
};
@Test
public void monitorTest() throws InterruptedException {
monitor.enterWhen(capacityGuard);
try {
list.add("Samuel");
System.out.println("Samuel");
} finally {
monitor.leave();
}
if (monitor.enterWhen(capacityGuard, 100, TimeUnit.MILLISECONDS)) {
try {
list.add("Jason");
System.out.println("Jason");
} finally {
monitor.leave();
}
}
}
}
결과
Samuel