Lock class abstract

A mutual-exclusion lock: serializes access to a shared resource across asynchronous code, similar to Java's synchronized.

A Lock can be reentrant (backed by a Zone, see the Lock.new reentrant parameter) or non-reentrant, in which case it behaves like an asynchronous executor with a capacity of 1 (only one call to synchronized runs at a time; a nested call from within an already-held non-reentrant lock deadlocks).

Share one instance (a final field or a top-level variable) between all the calls to serialize: a Lock created in each call locks nothing.

final lock = Lock();

Future<int> next() => lock.synchronized(() async {
  // Only one block of this lock runs at a time, the others wait.
  return await readAndIncrementCounter();
});

A Lock works within one isolate. Use a GlobalLock (package:synchronized/global_lock.dart) across isolates, processes or browser tabs.

Available extensions

Constructors

Lock({bool reentrant = false})
Creates a Lock.
factory

Properties

canLock → bool
Whether calling synchronized right now would be able to acquire the lock without waiting.
no setter
hashCode → int
The hash code for this object.
no setterinherited
inLock → bool
For a reentrant lock, whether the current Zone is nested inside a synchronized call on this lock (so a further nested call would not deadlock).
no setter
locked → bool
Whether the lock is currently held, i.e. a call to synchronized is currently running (or waiting for a nested synchronized call to finish, for a reentrant lock).
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
synchronized<T>(FutureOr<T> computation(), {Duration? timeout}) → Future<T>
Runs computation once this lock is available, preventing any other call to synchronized on this lock from running concurrently.
synchronizedSync<T>(T computation(), {Duration? timeout}) → FutureOr<T>

Available on Lock, provided by the TekartikLockExtension extension

Runs the synchronous computation, returning its result directly (not wrapped in a Future) if this lock can be acquired immediately (see Lock.canLock).
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited