在Android上解锁ReentrantLock时出现IllegalMonitorStateException

时间:2014-08-25 08:48:06

标签: java android synchronization reentrantlock

我正在使用ReentrantLock推荐的做法(锁定,然后是try-block中的实际代码,最后解锁,请参阅下面的代码示例)。有时(非常非常罕见)我在解锁期间遇到java.lang.IllegalMonitorStateException异常。为什么会这样?也许它与Android的Java VM实现有某种关系。

错误:

java.lang.IllegalMonitorStateException
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:126)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1232)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:430)
at com.example.dummy.backend.model.Model.unlock(Model.java:283)
at com.example.dummy.backend.engine.Engine.removeOldInstances(Engine.java:712)
at com.example.dummy.backend.engine.Engine$ProcessOnResumeWorkInBackground.doInBackground(Engine.java:836)
at com.example.dummy.backend.engine.Engine$ProcessOnResumeWorkInBackground.doInBackground(Engine.java:790)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)

代码示例(略微简化):

myLock.lock();
try {
        LinkedList<MyClass> myClassInstances = model.getMyClassInstances();
        Iterator<MyClass> iterator = myClassInstances.iterator();
        while (iterator.hasNext()) {
                MyClass myClassInstance = iterator.next();
                boolean toBeRemoved = true; // simple condition here
                if (toBeRemoved) {
                        logger.info("Removing old myClassInstance " + myClassInstance.getTimestamp());
                        iterator.remove();
                        Cache.removeMyClassByCodeAndTimestamp(myClassInstance);
                }
        }
} finally {
        myLock.unlock();
}

0 个答案:

没有答案