Wednesday, October 11, 2006

Thread Priority and Scheduling

If there is more than one thread in a Ready state at a given time, the thread scheduler must decide which thread should run first, and it does so based on the fixed priority scheduling algorithm.

In fixed priority scheduling, the scheduler chooses the highest-priority thread to run first. Lower-priority threads will run only when the highest-priority thread dies, yields, or enters one of the Not Runnable states. If an even higher-priority thread becomes Ready, it should usually pre-empt the original thread and gain control of the CPU.

If all Ready threads have the same priority, the thread scheduler chooses a thread at random. It won't necessarily be the one that has waited longest. If a high priority thread has a run method with no pauses in the code – sleep or wait method calls, for example – it will keep control of the CPU until its run method finishes. This is known as a selfish thread.

In pre-emptive implementation, such threads will either give the CPU up by themselves or be pre-empted by a thread of higher priority.

In time-slicing implementation, a thread runs for a specific time and then enters the runnable state, at which point the scheduler decides wether to return to the thread or schedule a different thread. This means that if more than one thread has equal, highest priority, the threads take turns at the CPU for finite slots of time until one finishes or a higher-priority thread becomes ready. (Win 95/NT)

Not all platforms implement scheduling in the same way, you need to be careful when writing programs that depend on manipulating thread priorities, because they may not run in the same way on all Java Virtual Machines (VMs).

No comments: