Java Concurrency - Synchronized Statement

Java Conceptuel Diagram

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

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

Documentation / Reference





Discover More
Java Conceptuel Diagram
Java Concurrency - Fine-grained synchronization

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose: class MsLunch has two instance fields, c1 and c2, c1 and c2 are never used together....
Java Conceptuel Diagram
Java Concurrency - Lock Objects (java.util.concurrent.locks)

java/util/concurrent/locks/package-summaryLock Object package is a High Level Concurrency of the java.util.concurrent. For low-level, intrinsic lock (monitor), see . There is interfaces and classes that...
Java Conceptuel Diagram
Java Concurrency - Synchronization (Thread Safety)

in java. Java offers two basic synchronization idioms: synchronized methods synchronized statements final fields, which cannot be modified after the object is constructed, can be safely read...



Share this page:
Follow us:
Task Runner