Monday, 13 July 2015

Java Thread Priorities

Java assigns to each thread a priority that determines how that thread should be treated with respect to the others.

Thread priorities are integers that specify the relative priority of one thread to another. As an absolute value, a priority is meaningless; a higher-priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next. This is called a ontext switch.

The rules that determine when a context switch takes place are simple:

  • A thread can voluntarily (on its own) relinquish control. This is done by explicitly yielding, sleeping or blocking on pending I/O. In this scenario, all other threads are examined, and normally the highest-priority thread that is ready to run is given the CPU.

  • A thread can be pre-empted by a higher-priority thread. In this case, a lower priority thread that does not yield the processor is simply pre-empted no matter what it is doing, by a higher priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. Some OS support non-preemptive priority based scheduling. In such case a high priority thread gets chance only when low priority thread completes.
  • In cases where two threads with the same priority are competing for CPU cycles, the situation is a bit complicated. For OS such as windows 98, threads of equal priority are normally time-sliced automatically in the round-robin fashion. For other types of OS's, thread of equal priority must voluntarily (on their own) yield (give) control to their peers. If they do not, the other threads will not run.

Note: Problems can arise from the differences in the way that O.S.’s context-switch threads of equal priority.

No comments:

Post a Comment