Java Concurrency - Synchronized Statement

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

1 - About

Another way to create synchronized code is with synchronized statements.

Advertising

3 - 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);
 
}

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

5 - Usage

  • Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking a unique statement (in our case nameList.add)
  • Invoking other objects' methods from synchronized code can create problems. See Liveness.
  • Synchronized statements are also useful for improving concurrency with fine-grained synchronization.

6 - Documentation / Reference

Advertising