tryExclusive static method

Future<WayfinderFileLock?> tryExclusive(
  1. File file
)

Takes the lock without waiting for a holder; null while another holder has it. Creates file and its directory when missing.

An isHeld probe holds a shared lock on the file for an instant, and must not read as a holder, so a refused attempt is tried again for up to 100 milliseconds before this returns null.

Implementation

static Future<WayfinderFileLock?> tryExclusive(File file) async {
  final watch = Stopwatch()..start();
  var delay = const Duration(milliseconds: 1);
  while (true) {
    final lock = await _attempt(file);
    if (lock != null) return lock;
    final left = _probeTolerance - watch.elapsed;
    if (left <= Duration.zero) return null;
    await Future<void>.delayed(delay < left ? delay : left);
    if (delay < const Duration(milliseconds: 32)) delay *= 2;
  }
}