synchronized<T> function

T synchronized<T>(
  1. Object monitor,
  2. T action()
)

Runs the given action in a critical section, ensuring only one execution at a time per monitor object.

This function provides an easy and safe way to serialize access to a shared resource. It retrieves a lock associated with the monitor and queues the action to be executed when it's safe to do so.

Reentrant calls from the same Dart Zone are allowed (i.e., nested synchronized() calls on the same monitor will execute immediately).

Example:

final lockTarget = Object();

void criticalWrite() {
  synchronized(lockTarget, () {
    // only one call at a time per lockTarget
    writeToDatabase();
  });
}

Implementation

T synchronized<T>(Object monitor, T Function() action) {
  final lock = _lockRegistry.getLock(monitor);
  return lock.synchronized(action);
}