이 질문은 Synchronizing on an Integer value을 기반으로합니다.Integer에서 동기화하면 NullPointerException이 발생합니다.
거기에 솔루션은 거기에 작은 문제가 ConcurrentHashMap
에서 값을 삭제하는 방법에 대한 우려를 해결하지 않는 것 같습니다.
import java.util.concurrent.ConcurrentHashMap;
public class Example {
private final ConcurrentHashMap<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<Integer, Integer>();
public void doSomething(int i) {
synchronized (getLockForId(i)) {
concurrentHashMap.remove(i);
}
}
public Integer getLockForId(int id) {
concurrentHashMap.putIfAbsent(id, id); // I want to replace these two
// operation with single one
// since it seems the cause of
// NPE
return concurrentHashMap.get(id);
}
public static void main(String[] args) {
final Example example = new Example();
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
example.doSomething(++i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
example.doSomething(++i);
}
}
}).start();
}
}
문제는 항상 NullPointerException
을 초래한다는 것이다 프로그램 아래했다는 것을 해결한다. 내 첫 번째 분석은 null에 할당 된 값을 삭제하므로 NullPointerException
이 원인입니다. 그래서 나는 아래에했다
Object obj = new Object();
synchronized (obj) {
obj = null;
}
그러나 위의 결과는 NullPointerException
이되지 않습니다. 그래서 내 질문에 위의 경우에 NullPointerException
을 던지고있는 이유는 무엇입니까? 이NullPointerException
를 던질 것이라고, 다른 하나 돌아 null
이 질문은 사실 값에 동기화
과 같을 것이다 Integer * 객체에 동기화 *를 기반으로합니다. – Aubin
완료되면 왜지도에서 값을 제거해야합니까? –
@NikitaBeloglazov 결국 제거해야 할 부분이 있어야합니까? 그 점이 동기화되어야하는 문제입니다. 나는 그 때 다른 해결책을 찾지 못했다. –