import java.util.concurrent.StructuredTaskScope;
import java.lang.Thread;

public class ScopedThread {
  private record V(String v){}
  
  private static final ScopedValue<V> VAL = ScopedValue.newInstance();

  public void printMyVal(){
    System.out.println(VAL.get());
  }

  public void test(String ...values) {
    for (String s : values) {
      ScopedValue.runWhere(VAL, new V(s), () ->{
          try (var scope = new StructuredTaskScope<String>()) {            
            scope.fork(() -> childTask(1));
            scope.fork(() -> childTask(2));
            try {
              scope.join();
            } catch(InterruptedException ex) {
              Thread.currentThread().interrupt();
            }
        }});
      }    
  }
  
  String childTask(int id) {
    // set name of thread - where do I execure?
    Thread.currentThread().setName("thread-" + id);    
    // modify "implicit parameter" from VAL by adding id
    ScopedValue.runWhere(VAL, new V(VAL.get().v + id), () ->{
      var val = "Task_%s: VAL=%s thread=%s".formatted(id, VAL.get(), Thread.currentThread().getName());
      System.out.println(val);
    });
    return "";
  }
  
  public static void main(String[] args) {
    var s = new ScopedThread();
    s.test("one", "two", "three");
  }
}
