4.5.4 Locks, Objects and ``synchronized''

Java allows each object within the JVM to be used as a lock. When an object is viewed as a lock, then only one thread can be in possession of the object lock at any time. This allows Java programmers to implement mutual exclusion between threads.

To use an object as a lock, the key word synchronized is used. In the following code, the block of code following synchronized(foo) is only executed when the thread can obtain the lock implemented by foo. If the lock is held by some other thread, then the thread blocks until the lock becomes free and it can grab it.

   ...
   // foo is out of fuel
   // only one thread need put fuel in
   synchronized(foo) {
      if(foo.empty())
         foo.addFuel();
   }
   // carry on in a fueled foo
   ...

If synchronized is used to decorate a method declaration eg.

class foo {
    synchronized void bar() {
       doStuff();
    }
}
then only one thread can be executing the bar on a particular instance of foo at a time. If there are multiple instances of foo, then a thread can be in each of the instances at a time. This usage is equivalent to putting synchronized(this) around the block of code implementing the method.

Ian Wakeman 2005-02-22