Java Reference
In-Depth Information
FIGURE 12-40
Because the same thread already owns the monitor, the code executes. If it
did not, then a deadlock condition would result. Deadlock is a condition where
two locks each are waiting on the other to release before execution can continue.
The execution of synchronized code is mutually exclusive in time for separate
threads, not for the same thread. Figure 12-41 displays lines 523 through 532 of
the WebStocks servlet code. When two different threads call the method begin-
ning on line 523, addToUserStocks(), the first thread gets the monitor and the
second thread must wait until the monitor is released. This is because the
database access on line 529 is synchronized on the StockTrackerDB object.
FIGURE 12-41
Understanding Synchronization
Synchronization can be difficult to understand. As an analogy,
let three motorcycles represent three methods or blocks of code,
three people represent three threads, and one helmet represent
the object providing the lock. Only the person with the helmet
can operate one of the three motorcycles, so the motorcycles
are synchronized on the helmet. Without the helmet, the other
two people (threads) must wait to use one of the remaining
motorcycles, even though they are not in use. When the first
person returns the helmet, the next person may use it with any
of the synchronized motorcycles. Waiting for a helmet makes the
motorcycles thread-safe!
Search WWH ::




Custom Search