سؤال

I've recently rebuilt the power managing sections of my app to reduce complexity. Amongst the changes were the reuse of wakelocks; specifically, threads receive a wakelock upon creation and then acquire/release it as necessary until killed. I've discovered that this results in wakelocks that do not always release when release() is called. The code that causes the problem is, at its essence, given here:

// 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!");

My questions to you are:

  1. Has anyone else encountered this?
  2. Are wakelocks meant to be reused in this way?
  3. If yes to #2, is this a bug?
  4. If no to #2, did I miss this somewhere in the documentation?
هل كانت مفيدة؟

المحلول

I think I found out what was going on. According to the WakeLock documentation, wakelocks by default require a balanced number of calls to acquire() and release(). If this doesn't happen, release() won't actually release the lock. My code has nested tasks that use the same wakelock for microsleeping purposes. If one of them, say, acquires the wakelock once more than it releases it before returning control a higher level in the chain (e.g., if an improperly handled interrupt occurs), then the lock will never be released! I found this out by looking into setReferenceCounted() and WakeLock.toString(), the latter of which will tell you how many times acquire() has been called without a balancing release(). Hopefully this helps anyone else who encounters a similar problem!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top