A special type of error that you need to avoid that relates 'specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y.lf the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for two reasons: In general, it occurs only rarely, when the two threads time-slice in just the right way.

• It may involve more than two threads and two synchronized objects. (That is, . deadlock can occur through a more convoluted sequence of events than just described.) To understand deadlock fully, it is useful to see it in action. The next example creates two classes, A and B, with methods foo() and bare() respectively, which pause' briefly before trying to call a method in the other class. The main class, named Deadlock, creates an A and a B instance, and then starts a second thread to set up the deadlock condition. The foo( ) and bare ) methods use sleep ) as a way to force the deadlock condition to occur.

When you run this program, you will see the output shown here: MainThread entered RacingThread MainThreadtrying to call B.last() RacingThread trying to call A'.last () Because the program has deadlocked, you need to press CfRL-C to end Ihe program. You can see a full thread and monitor cache dump by pressing BREAK on a PC (or  Solaris), You will see That Racing Thread owns the monitor on b, while it is waiting for the monitor on a. At the same time, Main Thread owns it and is waiting to get b. This program will never complete, As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the first conditions that should check for.

Share This