我最近重建了我的应用程序的电源管理部分,以降低复杂性。这些更改包括对唤醒的重用;具体来说,线程在创建时接收一个唤醒,然后根据需要获取/释放它,直到终止。我发现,这会导致在调用release()时不总是释放唤醒。造成这个问题的代码本质上是在这里给出的:
// Get the lock for the first time, acquire it, and do some work.
WakeLock wakelock = receiveFirstWakeLock();
wakelock.acquire();
doWork();
// When work is finished, release the lock.
// Typically this lock is released very quickly.
wakelock.release();
// Re-acquiring the lock for the next bout of work always works.
wakelock.acquire();
doWork();
// In my full code, "wakelock" didn't appear to be releasing properly.
// I hypothesized that it might just be taking a little while
// so I tried this to see how long it would take.
// I found that it sometimes *never* releases!
wakelock.release();
while (wakelock.isHeld())
Thread.yield();
Log.d("Test","Released the lock!");我对你的问题是:
发布于 2013-09-01 23:38:35
我想我知道发生了什么。根据WakeLock文档,默认情况下,唤醒需要均衡地调用acquire()和release()。如果不发生这种情况,release()实际上不会释放锁。我的代码有一些嵌套的任务,它们使用相同的唤醒锁来实现微睡眠。如果其中一个,比如说,在返回控制链中的更高级别(例如,如果发生了处理不当的中断)之前,获得了锁一次而不是释放它,那么锁将永远不会被释放!我通过查看setReferenceCounted()和WakeLock.toString()发现了这一点,后者将告诉您acquire()在没有平衡release()的情况下被调用了多少次。希望这能帮助其他遇到类似问题的人!
https://stackoverflow.com/questions/18563399
复制相似问题