user2233706
user2233706

Reputation: 7225

Is there race condition when multiple Future/Timer complete simultaneously

Can there be a race condition if multiple Timer/Future complete simultaneously in Dart? For example, is there a race condition when accessing the test and test structures in the Timer complete handler in the following code?

import 'dart:async';

void main() {
  Map<String, int> test = {};
  List<int> test2 = [];

  Timer t1 = Timer(Duration(seconds: 1), () {
    test['a'] = 45;
    test2.add(1);
  });

  Timer t2 = Timer(Duration(seconds: 1), () {
    test['b'] = 67;
    test2.add(2);
  });

  Timer t3 = Timer(Duration(seconds: 2), () {
    print(test);
    print(test2);
  });
}

Or are Timer/Future completions processed synchronously by the main thread? Can the code within two callbacks be interwoven?

Upvotes: 0

Views: 1838

Answers (1)

jamesdlin
jamesdlin

Reputation: 90125

Each Dart isolate executes code in a single thread. Asynchronous code running in a single Dart isolate can run concurrently but not in parallel.

In general, if the callbacks themselves do asynchronous work, then they can be interleaved. Any await (which is equivalent to any Future.then() callback) is a point where execution returns to the event loop, interrupting your asynchronous function.

In your particular example, your callbacks are fully synchronous and cannot be interrupted. Your Timers probably will fire in a defined order since events are added to FIFO queues. However, that seems brittle, and I do not think that it would be a good idea to rely on callback ordering.

Also see: Prevent concurrent access to the same data in Dart.

Upvotes: 2

Related Questions