Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8293066

CompletableFuture and InheritableThreadLocal return null

    XMLWordPrintable

Details

    Description

      ADDITIONAL SYSTEM INFORMATION :
      Windows 10 19044.1889 (x64)

      openjdk 19 2022-09-20
      OpenJDK Runtime Environment (build 19+36-2238)
      OpenJDK 64-Bit Server VM (build 19+36-2238, mixed mode)


      A DESCRIPTION OF THE PROBLEM :
      // Why can only first time get the correct value ?
          public static void main(String[] args) {

              for (int i = 0; i < 9; i++) {
                  var tl = new InheritableThreadLocal<String>();
                  tl.set("value");
                  CompletableFuture.runAsync(() -> System.out.println(tl.get())).join();
              }

          }

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Just run

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      value
      value
      value
      value
      value
      value
      value
      value
      value
      ACTUAL -
      value
      null
      null
      null
      null
      null
      null
      null
      null

      ---------- BEGIN SOURCE ----------
      import java.util.concurrent.CompletableFuture;

      public class Demo {

          public static void main(String[] args) {

              for (int i = 0; i < 9; i++) {
                  var tl = new InheritableThreadLocal<String>();
                  tl.set("value");
                  CompletableFuture.runAsync(() -> System.out.println(tl.get())).join();
              }

          }

      }
      ---------- END SOURCE ----------

      FREQUENCY : always


      Attachments

        Activity

          People

            dl Doug Lea
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated: