synchronized 1.5.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 93

synchronized

Build Status

Basic lock mechanism to prevent concurrent access to asynchronous code

Goal

You were missing hard to debug deadlocks, here it is!

The goal is to propose a solution similar to critical sections and offer a simple synchronized API à la Java style. It provides a basic Lock/Mutex solution to allow features like transactions.

The name is biased as we are single threaded in Dart. However since we write asychronous code (await) like we would write synchronous code, it makes the overall API feel the same.

The goal is to ensure for a single process (single isolate) that some asynchronous operations can run without conflict. It won't solve cross-process (or cross-isolate) synchronization.

For single process (single isolate) accessing some resources (database..), it can help to

  • Provide transaction on database system that don't have transaction mechanism (mongodb, file system)
  • In html application make sure some asynchronous UI operation are not conflicting (login, transition)

Feature

  • Synchronized block are reentrant
  • Timeout support
  • Support for non-reentrant lock (not using Zone)
  • Consistent behavior (i.e. if it is unlocked calling synchronized grab the lock)
  • Values and Errors are properly reported to the caller
  • Work on Browser, DartVM and Flutter
  • No dependencies (other than the sdk itself)

It differs from the pool package used with a resource count of 1 by supporting a reentrant option

Usage

A simple usage example:

import 'package:synchronized/synchronized.dart';

main() async {
  // Use this object to prevent concurrent access to data
  var lock = new Lock();
  ...
  await lock.synchronized(() async {
    // Only this block can run (once) until done 
    ...
  });
}

If you need a re-entrant lock you can use

var lock = new Lock(reentrant: true);
// ...
await lock.synchronized(() async {
  // do some stuff
  // ... 
  
  await lock.synchronized(() async {
    // other stuff
  }
});

A basic lock is not reentrant by default and does not use Zone. It behaves like an async executor with a pool capacity of 1

var lock = Lock();
// ...
lock.synchronized(() async {
  // do some stuff
  // ...
});

The return value is preserved

int value = await lock.synchronized(() {
  return 1;
});

How it works

Each Lock object keep a list of pending tasks. The next tasks is executed once the previous one is done

Re-entrant locks uses Zone to know in which context a block is running in order to be reentrant.

Example

Consider the following dummy code

Future writeSlow(int value) async {
  await new Future.delayed(new Duration(milliseconds: 1));
  stdout.write(value);
}

Future write(List<int> values) async {
  for (int value in values) {
    await writeSlow(value);
  }
}

Future write1234() async {
  await write([1, 2, 3, 4]);
}

Doing

write1234();
write1234();

would print

11223344

while doing

lock.synchronized(write1234);
lock.synchronized(write1234);

would print

12341234

The Lock instance

Have in mind that the Lock instance must be shared between calls in order to effectively prevent concurrent execution. For instance, in the example below the lock instance is the same between all myMethod() calls.

class MyClass {
  Lock _lock = new Lock();

  Future<void> myMethod() async {
    await _lock.synchronized(() async {
      step1();
      step2();
      step3();
    });
  }
}

Typically you would create a global or static instance Lock to prevent concurrent access to a global resource or a class instance Lock to prevent concurrent modifications of class instance data and resources.

Features and bugs

Please feel free to:

Changelog

1.5.2

  • Remove dev_test dependency

1.5.1

  • Dart2 stable support

1.5.0

  • Deprecate SynchronizedLock and synchronized

1.4.0

  • Re-use non-reentrant lock in synchronized method

1.3.0

  • Add non-reentrant lock that do not use Zone

1.2.1

  • implicit-casts: false (testing dart2 support)

1.2.0

  • Use generic instead of 2.0 deprecated comments

1.1.0

  • Fix inner task issue, next outer task will wait for all inner tasks to terminate
  • Properly handle nested thrown error

1.0.0

  • Bump to version 1.0.0

0.1.0

  • Initial version

example/synchronized_example.dart

import 'dart:async';
import 'dart:io';
import 'package:synchronized/synchronized.dart';

Future writeSlow(int value) async {
  await Future.delayed(Duration(milliseconds: 1));
  stdout.write(value);
}

Future write(List<int> values) async {
  for (int value in values) {
    await writeSlow(value);
  }
}

Future write1234() async {
  await write([1, 2, 3, 4]);
}

class Demo {
  Future test1() async {
    stdout.writeln("not synchronized");
    //await Future.wait([write1234(), write1234()]);
    write1234();
    write1234();

    await Future.delayed(Duration(milliseconds: 50));
    stdout.writeln();
  }

  Future test2() async {
    stdout.writeln("synchronized");

    var lock = Lock();
    lock.synchronized(write1234);
    lock.synchronized(write1234);

    await Future.delayed(Duration(milliseconds: 50));

    stdout.writeln();
  }

  Future readme1() async {
    var lock = Lock();

    // ...
    await lock.synchronized(() async {
      // do some stuff
    });
  }

  Future readme2() async {
    var lock = Lock();
    if (!lock.locked) {
      lock.synchronized(() async {
        // do some stuff
      });
    }
  }

  Future readme3() async {
    var lock = Lock();
    int value = await lock.synchronized(() {
      return 1;
    });
    stdout.writeln("got value: ${value}");
  }
}

main() async {
  var demo = Demo();

  await demo.test1();
  await demo.test2();
  await demo.readme1();
  await demo.readme1();
  await demo.readme3();
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  synchronized: ^1.5.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:synchronized/synchronized.dart';
  
Version Uploaded Documentation Archive
1.5.3 Sep 20, 2018 Go to the documentation of synchronized 1.5.3 Download synchronized 1.5.3 archive
1.5.2 Sep 13, 2018 Go to the documentation of synchronized 1.5.2 Download synchronized 1.5.2 archive
1.5.1+1 Aug 9, 2018 Go to the documentation of synchronized 1.5.1+1 Download synchronized 1.5.1+1 archive
1.5.1 Jul 24, 2018 Go to the documentation of synchronized 1.5.1 Download synchronized 1.5.1 archive
1.5.0+1 Jun 12, 2018 Go to the documentation of synchronized 1.5.0+1 Download synchronized 1.5.0+1 archive
1.5.0 Jun 12, 2018 Go to the documentation of synchronized 1.5.0 Download synchronized 1.5.0 archive
1.4.0 Apr 5, 2018 Go to the documentation of synchronized 1.4.0 Download synchronized 1.4.0 archive
1.3.0 Mar 4, 2018 Go to the documentation of synchronized 1.3.0 Download synchronized 1.3.0 archive
1.2.1 Mar 1, 2018 Go to the documentation of synchronized 1.2.1 Download synchronized 1.2.1 archive
1.2.0 Jan 26, 2018 Go to the documentation of synchronized 1.2.0 Download synchronized 1.2.0 archive

All 16 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
92
Health:
Code health derived from static analysis. [more]
90
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
93
Learn more about scoring.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:synchronized/synchronized.dart.

Health issues and suggestions

Document public APIs (-10 points)

8 out of 8 API elements (library, class, field or method) have no adequate dartdoc content. Good documentation improves code readability and discoverability through search.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
Dev dependencies
build_runner >=0.9.2
build_test >=0.10.3
chrome_travis
test >=0.12.0