Discussion Locked

Java Thread Priority

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
In reading Java's documentation on their site, it seems that java will execute a lower priority thread before a higher one if there is a starvation situation. How can I demonstrate that this is happening and then prevent it?

2 replies

by rakesh goenka

In a starvation situation, Java will execute a higher priority thread and lower priority threads will usually not get a chance. I have observed varied behavior on different OS, esp Solaris and Windows NT/2000 boxes.

Here is how you can demonstrate this case:

Create three threads:
1. High-priority - Executes appending strings in a tight loop endlessly. This will hog the CPU
2. High-priority - Displays the string from above
3. Low-priority - Displays an alive message.

You will see that low-priority thread does not get much of a chance to execute.

You may want to diagnose why you have a starvation situation first. If you do not have control over the code, there is not much you can do about it, except throwing more hardware or getting rid of the starving application.

But if you can change the code:
Introduce a small sleep (or yield if you are comfortable with Thread API), in all your threads "run" method. That allows other threads to run.

Hope that helps,

This discussion is closed to new replies.