Java Concurrency - Synchronized method

> Procedural Languages > Java > Java - Concurrency (Parallel Work)

1 - About

Synchronized method

Advertising

3 - Syntax

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

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

4 - Process

A synchronized method:

  • performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed.
  • It locks:
    • If the method is an instance method, the monitor associated with the instance for which it was invoked.
    • If the method is static, the monitor associated with the Class object that represents the class in which the method is defined.
  • unlock the same monitor if the method's body is ever completed, either normally or abruptly.

5 - 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:

  • It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Advertising

6 - Type

6.1 - 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.

7 - Documentation / Reference

lang/java/concurrency/method.txt · Last modified: 2017/10/27 15:54 by gerardnico