11

In order to synchronize/queue access to a shared resource, I am about to use a Semaphore, aided by a wait loop.

In order not to run into CPU pegging, I would like to sleep() a little bit inside that while loop.

I searched the http://developer.android.com reference and found two such sleep() functions and I am confused as to which one fits which scenario:

  1. Thread.sleep()
  2. SystemClock.sleep()

Which one better suits the case I described and why?

srf
  • 2,410
  • 4
  • 28
  • 41

2 Answers2

19

First of all, do you really need a wait loop? You can typically solve your problems using proper notifications, i.e. having an Object, calling wait() and notify() on it or other means (like a blocking queue, or Semaphore.acquire() in your case).

That said, if you really want a polling loop (which you really shouldn't do unless you have to), I'd stick with Thread.sleep(). There's not much of a difference, as the documentation says, except that you have the option to interrupt a Thread.sleep(). Don't rid yourself the option to do so.

Note that in case of Thread.sleep(), you're going to have to catch that exception - if you're extremely lazy, you'll probably stick with SystemClock.sleep().

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
EboMike
  • 76,846
  • 14
  • 164
  • 167
  • Thanks for this great and timely clarification. I just discovered that `Semaphore.acquire()` may be the best option. – srf Apr 29 '11 at 22:26
  • If you're using wait() you need to do so in a loop. wait() can return before the call to notify(). See http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait() for correct usage. "Seven Concurrency Models in Seven Weeks: When Threads Unravel" covers this topic well. – Jonathan Jul 22 '14 at 16:22
1

The truth is:

Thread.sleep(n) could be interrupted within a call like AsyncTask by using asyncTask.cancel(true)

SystemClock.sleep(n) seems to ignore any interrupted command, thus it could be a risk of memory leak when you use it similar like here: https://github.com/square/leakcanary/blob/master/leakcanary-sample/src/main/java/com/example/leakcanary/MainActivity.java

LiangWang
  • 8,038
  • 8
  • 41
  • 54
  • They're not related. That example just uses a sleep in order to give you time to rotate the screen, which causes a leak. – Matt Quigley May 06 '16 at 01:59