// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import jdk.incubator.concurrent.ScopedValue;
import jdk.incubator.concurrent.StructuredTaskScope;

public class SV20 {
    public static final ScopedValue<Integer> GLOBAL_V = ScopedValue.newInstance();
    public static void dump() {
        System.out.printf("%d : %d\n", Thread.currentThread().getId(), SV20.GLOBAL_V.get());
    }
    public static void test() {
        for(int i = 0; i < 3; i++) {
            try {
                Thread.sleep(10);
            } catch(InterruptedException ex) {
            }
            dump();
        }
    }
    public static void main(String[] args) throws Exception {
        try(final StructuredTaskScope<Integer> scope = new StructuredTaskScope<Integer>()) {
            scope.fork(() -> { ScopedValue.where(GLOBAL_V, 123).run(() -> test()); return 0; } );
            scope.fork(() -> { ScopedValue.where(GLOBAL_V, 456).run(() -> test()); return 0; } );
            scope.fork(() -> { ScopedValue.where(GLOBAL_V, 789).run(() -> test()); return 0; } );
            scope.join();
        }
    }
}
