Table of Contents

Java Concurrency - Synchronized method

About

Synchronized method

Syntax

To make a method synchronized, simply add the synchronized keyword to its declaration:

public synchronized void increment() {
      c++;
}

Process

A synchronized method:

Effect

When a thread invokes a synchronized method, it automatically acquires a class level lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

Synchronized Method has two effects:

Type

Constructor

constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

When constructing an object that will be shared between threads, be very careful that a reference to the object does not “leak” prematurely.

For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor:

instances.add(this);

But then other threads can use instances to access the object before construction of the object is complete.

Documentation / Reference