I do not know why but i created a thread where i am using Thread.sleep(1000) and its working in 8 out of 10 devices but not working in rest 2 devices.
Not working means, thread is sleeping for around 0.5 sec instead of 1 sec and i can see it in logs.
So there is no guarantee that thread will sleep for exact amount of time ?
What could be the possible issues ?
Same code is working in almost devices.
CodePudding user response:
There is no guarantee that Thread.sleep
will sleep for an exact amount of time. What the javadoc actually says is:
"Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers."
Sleeping longer than expected it not unexpected. For example, it can happen if the device's cores are all busy doing other things when the "sleep" is due to end.
However, a sleep()
call returning significantly sooner than requested sleep time is not expected behavior.
I suspect that the real cause is:
Your thread is getting an interrupt and your code is squashing the exception ... so you don't notice it. An interrupt send to a sleeping thread will cause the
sleep
call to return early.Your
sleep
call's argument is different to what you think.Possibly a system clock adjustment happened at the wrong time ... though I would expect this to be a "once in a blue moon" event.
This is an artifact of an emulator, a debugger or something like that "messing" with the clock.
However, if this is a real effect and not caused by something that you are doing, then I would say that it is a candidate for reporting as a bug to the vendor of the device. But you would need a way to demonstrate the problem repeatably; i.e. a minimal reproducible example to include in your bug report.
CodePudding user response:
The sleep() documentation warns that it's not precise: https://developer.android.com/reference/java/lang/Thread#sleep(long)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.