synchronized<T> method

T synchronized<T>(
  1. T action()
)

Executes the action within a synchronous synchronized block.

This function attempts to acquire the lock immediately. If the lock is already held by a different Zone, it will throw a ReentrantSynchronizedException as it cannot wait asynchronously. Reentrant calls from the same Zone are allowed and execute immediately.

Example:

lock.synchronized(() {
  // Do something synchronous
});

Implementation

T synchronized<T>(T Function() action) {
  // Handle reentrancy: if the current zone already holds the lock, execute immediately.
  if (_isLocked && _currentLockingZone == Zone.current) {
    _reentrantCount++;
    try {
      return action();
    } catch (e) {
      rethrow; // Re-throw the original exception
    } finally {
      _reentrantCount--;
      if (_reentrantCount == 0) {
        _currentLockingZone = null;
        _isLocked = false; // Release the lock
      }
    }
  } else { // Not reentrant, or lock is free
    // If lock is held by another zone, throw an error for synchronous call
    if (_isLocked) {
      throw ReentrantSynchronizedException('Synchronized lock is held by another zone. Cannot acquire synchronously.');
    }

    // Acquire lock and run immediately
    _isLocked = true;
    _currentLockingZone = Zone.current;
    _reentrantCount = 1; // First acquisition for this zone
    try {
      return action();
    } catch (e) {
      rethrow; // Re-throw the original exception
    } finally {
      _reentrantCount--;
      if (_reentrantCount == 0) {
        _currentLockingZone = null;
        _isLocked = false; // Release the lock
      }
    }
  }
}