synchronized Methods

Purpose:

synchronized is used in multi-threaded programming. Every object with synchronized methods is a monitor. The monitor lets only one thread at a time execute a synchronized method on the object.

Mechanics:

<other modifiers> synchronized <return type> <method name>(<parameter list>) {
/* Java statements */
}

Example:

public synchronized void addItem(Object obj) {
/* Java statements */
}

Usage:

  • synchronized is one of several possible modifiers that can appear anywhere in the space-separated list of modifiers.
  • A synchronized method works by locking the object when the method is invoked. If there are several synchronized methods, only one synchronized method can be active on an object at once; all other threads attempting to invoke synchronized methods must wait. When a synchronized method finishes executing, the lock on the object is released and the monitor lets the highest-priority ready thread attempting to invoke a synchronized method proceed.

Restrictions:

Unless you are doing multithreaded programming, you do not need synchronized methods.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu