Table of Contents

Java Concurrency - Synchronized Statement

About

Another way to create synchronized code is with synchronized statements.

Syntax

Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.

public void addName(String name) {
    // this refer to the instance
    // the addName method needs to synchronize changes to lastName and nameCount
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    
    // but also needs to avoid synchronizing other objects' methods
    nameList.add(name);
    
}

Process

The synchronized statement:

  1. computes a reference to an object;
  2. attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed.
  3. execute its body after the lock action has been performed
  4. unlock the same monitor if the execution of the body is ever completed, either normally or abruptly.

Usage

Documentation / Reference