shantanu
shantanu

Reputation: 2418

Thread sleep is inconsistance in android

I found a surprising things about Thread.sleep. Thread doesn't wake up in time. Let me explain. I create an activity (no service) and run a thread like the following.

Thread.sleep(50000); // 50 seconds
System.out.println("something");

Then i keep the activity in foreground and off the display (by pressing power button). Also i was logging in a file saved in sdcard. What i found that, After almost 10 min Thread delay 7.35 minutes to print instead of 50 seconds. Is it normal?? Can i trust on Thread.sleep()?

16:47:57 ---- START
-------- 
-------- (all are in time)
--------
16:57:07 -- (in time)
16:57:57 -- (in time)
17:05:38 --- (late)

Upvotes: 2

Views: 736

Answers (3)

shantanu
shantanu

Reputation: 2418

I found out that when you turn off the screen using power button then android go to sleep after sometimes. CPU also go to sleep when screen is off. That's whey Thread.sleep() is giving large delay. In my case my device was in sleep mode for 7.30 minute and when i turn on the screen cpu wake up and start the Thread again. By acquiring the Partial_wake_lock you can hold cpu to go to sleep even when you press the power button(not shutdown).

More details

Upvotes: 1

Givi
Givi

Reputation: 3283

You can try:

LockSupport.parkNanos(nanos)

Or other methods it provides. It's more accurate.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718678

Can i trust on Thread.sleep()?

You can trust it to behave as specified1. But the specification says that a sleep will cause the thread to stop for at least that number of milliseconds. Under some circumstances, it could stop for longer. For example, if there is a lot of work for a higher priority thread to do, a lower priority thread may not be woken from the sleep for a long time.


1 - Actually, in theory, it might not behave as specified. But you've tendered no evidence to support that ...

Upvotes: 2

Related Questions