0

Consider following code:

class AppState extends ChangeNotifier {
  List<int> collection = [];
  
  AppState() {
    Timer.periodic(
      const Duration(seconds: 1),
      (Timer t) async => await mutateCollection(),
    );
  }
  
  Future mutateCollection() async {
    collection.add(DateTime.now().millisecond);
    notifyListeners();
  }
  
  void mutateCollectionFromUI() {
    collection.add(DateTime.now().millisecond);
    notifyListeners();
  }

  void createNewCollectionFromUI() {
    collection = [];
    notifyListeners();
  }
}

Is it thread safe?

Maciej Pszczolinski
  • 1,623
  • 1
  • 19
  • 38
  • 1
    Everything is always threadsafe. There are no locks to be had. Code within an isolate runs in a single observable thread, and dataspaces are not shared between isolates. – Randal Schwartz Sep 01 '22 at 18:01
  • 2
    The above code is not multithreaded. Also you cannot have a data race in pure dart code. In order for a data race to occur you need there to be mutable state that is shared between two or more threads, and at least one thread has to do a write, the other thread can do either a read or write. In dart the only way to have multiple threads is via Isolates. Isolates do not share state between each other, which makes data races not possible. – mmcdon20 Sep 01 '22 at 18:15
  • thanks. these 2 above comments answers my doubts. – Maciej Pszczolinski Sep 01 '22 at 18:47
  • @mmcdon20 you can still have data races with a single thread. See this question for a basic example: https://stackoverflow.com/questions/42071051/dart-how-to-manage-concurrency-in-async-function – Renato Sep 01 '22 at 20:52
  • @Renato no, that is an example of a race condition, not a data race. They are not the same thing: https://stackoverflow.com/questions/11276259/are-data-races-and-race-condition-actually-the-same-thing-in-context-of-conc – mmcdon20 Sep 01 '22 at 21:23
  • Hard to remember the right definitions... but anyway, I think OP may be referring, as I did, to any kind of race condition as obviously Dart has no thread concurrency by design (even multiple Isolates must exchange messages and don't share memory directly). – Renato Sep 02 '22 at 08:34
  • I was referring only to thread safety. I know "standard race" may still happen. Thanks :) – Maciej Pszczolinski Sep 02 '22 at 08:57

0 Answers0