Reputation: 11452
Will Thread priority increases accuracy of Thread.sleep(50);
?
As we know Threads aren't accurate when you call sleep for 50ms, But does it increases accuracy by any mean? If thread is listed as MAX_PRIORITY
.
Will be thankful for any kind of explanation.
Upvotes: 7
Views: 598
Reputation: 53829
Yes it may make it more accurate.
Nevertheless, from Java Concurrency In Practice, by Brian goetz:
The thread priority mechanism is a blunt instrument, and it's not always obvious what effect changing priorities will have; boosting a thread's priority might do nothing or might always cause one thread to be scheduled in preference to the other, causing starvation.
It is generally wise to resist the temptation to tweak thread priorities. As soon as you start modifying priorities, the behavior of your application becomes platform-specific and you introduce the risk of starvation. You can often spot a program that is trying to recover from priority tweaking or other responsiveness problems by the presence of
Thread.sleep
orThread.yield
calls in odd places, in an attempt to give more time to lower-priority threads.
Therefore avoid changing the thread priorities and re-think your design if you really need your Thread.sleep(50)
to be that accurate!
Upvotes: 0
Reputation: 533520
The accuracy of sleep is down to the operating system. If you want greater accuracy you can use another OS. Another approach is don't sleep, you can busy wait instead. Or you can sleep for say 45 ms and busy wait for 5 ms.
If you have a task which you need to run 20 times per second, you are better off keeping track of when the tasks should run next and run it at the time (rather than wait a fixed amount of time) as what you do between sleeps will also take some time.
BTW This is what ScheduledExecutorService.scheduleAtFixedRate does for you.
It can sleep between task with micro-second accuracy (assuming the OS supports it) but it tries not to drift.
Upvotes: 5
Reputation: 26418
It is not related to the thread accuracy directly, but yes as you have given the MAX priority after the sleep of 50 milliseconds the JVM will pick any of the threads to process with the same MAX priority.
Upvotes: 0
Reputation: 52448
I can't imagine this would be the case. But the effects of thread priorities depends on the host operating system.
Upvotes: 0