Search code examples
multithreadingdartisolate

What is equivalent of JAVA ThreadLocal in dart?


static ThreadLocal<Uint8List> threadBuffer = new ThreadLocal<Uint8List>() {
@Override
  public byte[] initialValue() {
    return new byte[512];
 }
};

In Java, ThreadLocal is a class that provides thread-local variables. These are variables that are specific to a particular thread and are not shared among other threads.

So what is equivalent of this code snippets in dart.


Solution

  • Dart does not have thread-shared memory. Every isolate is single-threaded. Instead of concurrency, asynchronous code is event based.

    You may still want to have "semi-global" state which is preserved across awaits, but is not shared by other events happening in-between. You can use zones for that.

    Future<void> doSomething
    for (var id in [1, 2, 3]) {
      runZoned(zoneValues: {#id: 42}, () async { 
        await firstPart();
        var id = Zone.current[#id] as int; // Read id from zone
        print(id);
        await secondPart();
      });
    }
    

    This code runs the same code three times, but in different zones with different values bound to the #id symbol.

    That's the closest thing to thread-local values in Dart.