Site hosted by Angelfire.com: Build your free website today!
 

Mutual Exclusion

Java uses an approach based on monitors to express mutual exclusion in a program. A monitor collects together a number of functions (methods in Java's case) which are critical regions, and enforces the constraint the only one of those critical regions be runnable at any one time.

A thread may obtain exclusive access to an object/class via:

  • Method synchronization

    synchronized void f() {
        ... 
    }
  • Block synchronization

    void f() {
       synchronized(this) {
           ...
       }
    }
  • Class locking (locking static methods and fields)

    synchronized(C.class) {
        ...
    }

Synchronization method of the Object Class:

  • wait() - Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

    public final void wait() throws InterruptedException;
    public final void wait(long timeout) throws InterruptedException;
    public final void notify();
    public final void notifyAll();
  • notify(), notifyAll() - Wakes up a single/all thread(s) that is waiting on this object's monitor.