import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Test1 {
Map map = new HashMap();
Properties properties = new Properties();
public Test1() {
properties.put(“potato”, “じゃがいも”);
map.put(“a”, properties);
}
public void test() {
Thread test3 = new Thread(new Test3());
test3.start();
Thread test2 = new Thread(new Test2());
test2.start();
}
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.test();
}
class Test2 implements Runnable {
public void run() {
try {
Thread.sleep(500);
} catch (Exception e) {}
System.out.println(“Lock”);
synchronized (properties) {
for (int i=0; i<30; i++) {
try {
Thread.sleep(50);
} catch (Exception e) {}
properties.put("potato", "じゃがいも"+(i+1)+"個");
}
}
System.out.println("Unlock");
}
}
class Test3 implements Runnable {
public void run() {
for (int i=0; i<10; i++) {
System.out.println(properties.get("potato"));
try {
Thread.sleep(100);
} catch (Exception e) {}
}
}
}
}
Properties를 Reload 한다고 가정했을때, 멀티스레드 환경에서 안전한지 확인해보기 위해 만든 프로그램이다.
이 경우 put은 당연하고 get의 호출시에도 Lock 이 걸리는걸 확인했다.
그런데 Properties를 Map으로 대체하면 이게 Lock 이 안걸린다…
왜??
참고사이트
http://blog.xole.net/article.php?id=567
위 사이트를 보니 Map properties = Collections.synchronizedMap(new HashMap()); 로 변경하면 될것 같아서 해보니 되네…
음.. synchronized구문에는 Collections.synchronizedMap 로 만든 Map은 통용되지 않는듯.
]]>