问题描述
为什么会发生这种情况?事实是,监视器对象肯定不是null,但仍然经常会遇到此异常:
Why may this happen? The thing is that monitor object is not null for sure, but still we get this exception quite often:
java.lang.IllegalMonitorStateException: (m=null) Failed to get monitor for (tIdx=60)
at java.lang.Object.wait(Object.java:474)
at ...
引发此问题的代码是一个简单的池解决方案:
The code that provokes this is a simple pool solution:
public Object takeObject() {
Object obj = internalTakeObject();
while (obj == null) {
try {
available.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
obj = internalTakeObject();
}
return obj;
}
private Object internalTakeObject() {
Object obj = null;
synchronized (available) {
if (available.size() > 0) {
obj = available.keySet().iterator().next();
available.remove(obj);
synchronized (taken) {
taken.put(obj, Boolean.valueOf(true));
}
}
}
return obj;
}
public void returnObject(Object obj) {
synchronized (taken) {
taken.remove(obj);
}
synchronized (available) {
if (available.size() < size) {
available.put(obj, Boolean.valueOf(true));
available.notify();
}
}
}
我想念什么吗?
编辑:该异常发生在available.wait();
行中.
EDIT: The exception happens in available.wait();
line.
推荐答案
有关Object.wait的信息,请参见javadoc.
See the javadoc for Object.wait.
尤其是当前线程必须拥有该对象的监视器."和"[throws] IllegalMonitorStateException-如果当前线程不是对象监视器的所有者."也就是说,您需要在将要调用的对象上进行同步.
in particular "The current thread must own this object's monitor." and "[throws] IllegalMonitorStateException - if the current thread is not the owner of the object's monitor." That is, you need to synchronize on the object you are going to call wait on.
因此您的代码应为:
synchronized (available) {
available.wait();
}
这篇关于java.lang.IllegalMonitorStateException:(m = null)无法获取监视器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!