concept lock in category java

appears as: lock, locks, lock, locks
The Well-Grounded Java Developer

This is an excerpt from Manning's book The Well-Grounded Java Developer.

If you run the code, you’ll normally see an example of a deadlock—both threads will report receiving the update, but neither will confirm receiving the update for which they’re the backup thread. The reason for this is that each thread requires the other to release the lock it holds before the confirmation method can progress. This is illustrated in figure 4.3.

Figure 4.3. Deadlocked threads

To deal with deadlocks, one technique is to always acquire locks in the same order in every thread. In the preceding example, the first thread to start acquires them in the order A, B, whereas the second thread acquires them in the order B, A. If both threads had insisted on acquiring in order A, B, the deadlock would have been avoided, because the second thread would have been blocked from running at all until the first had completed and released its locks.

4.2.1. Synchronization and locks

As you already know, the synchronized keyword can be applied either to a block or to a method. It indicates that before entering the block or method, a thread must acquire the appropriate lock. For a method, that means acquiring the lock belonging to the object instance (or the lock belonging to the Class object for static synchronized methods). For a block, the programmer should indicate which object’s lock is to be acquired.