One of the problems you encounter while doing
multithreaded
programming is that you must often make sure that only one thread is
running a particular piece of code at the same time (perhaps to
protect some data structure or resource from simultaneous
access). In Java, this is achieved through
synchronization. It works like this:
- A block of code can be marked as synchronized. Each block
is associated with an object, and if no object is given it defaults
to the object that the code belongs to.
- A thread must own the monitor for the associated object to to be
permitted to enter a synchronized block. If it doesn't, it will wait
until it does.
- When a thread exits a synchronized block (or goes into a waiting
state while inside the block), the VM will check if
any other threads are waiting for the monitor, and in that case wakes
one of them.
While this method of synchronization is pretty
straightforward to
use, it is still
possible to get into a state of
deadlock if the
programmer is not careful. This is often the result of calling
synchronized blocks of code from within other synchronized
blocks. Avoid this at any cost...