Tuesday, February 12, 2008

Difference between Waiting and Yielding in JAVA Threads - Part 2


Yielding is the act of politely offering up your turn in the queue while maintaining your resources.

For example, suppose there are several person queuing up to use a bank’s automated teller machine(ATM).

In the Analogy-
People in Queue acting as Running Threads.
ATM acting as CPU.

Bingo! Your turn has arrived to use ATM. You know that this process will take a while because you’re going to transfer funds,check your balance, make a deposit, and so forth. So you decides to offer the person behind you to use ATM before you. This activity is referred as "YIELDING".Of course, you wouldn’t give that person your resources (money, ATM card, and so on). However, you would offer to give up your spot at the ATM (analogous to the CPU). The process of making this offer,even if there’s no one to accept it, is yielding. It may possible that person behind you is too nice and he/she says that please continue to use ATM, I would rather wait for you to finish. So it is possible that, even though you yielded, you may still get first access. In computer terms, though, when you yield, all threads (including your own) then get to compete for the lock on the object—your thread does not get a lesser or greater chance of getting the lock on the object. But what decides which thread actually wins that competition and gets access to the lock on the object? The thread scheduler does.

The thread scheduler is like an office manager. It takes threads into consideration and decides which thread should be allowed to run based on the underlying operating system, thread priorities, and other factors. There are two important points to note-
First, you must be aware that your thread of execution is not guaranteed to be next in line when you yield, even though you originally volunteered to give up the CPU. Once a thread yields and the CPU is taken by another thread, the original yielding thread does not have any special status in being next in line. It must wait and hope, like every other thread.
Second, it’s important to realize that your thread didn’t give up resources that you have exclusive locks on. That is, even though you’re letting someone else use the ATM, you didn’t give him your ATM card. When a thread yields, it steps out of the CPU, but it retains control over any resources it had originally marked for exclusive use.