Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample73 is run - what will be the output?

public class Sample73
{
    static final InheritableThreadLocal<String> TAG = new InheritableThreadLocal<>();

    public static void main(String[] args) throws InterruptedException
    {
        TAG.set("parent");
        Thread child = new Thread(() -> System.out.println(TAG.get()));
        child.start();
        child.join();
    }
}

  • A.parent
  • B.null
  • C.An empty line
  • D.A NullPointerException from get()

Answer: A

An InheritableThreadLocal passes the creating thread's value to each thread it creates, so the child sees parent. A plain ThreadLocal would give null here, because each thread would have its own unset value. Inheritance is a copy taken at construction, not a live link.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.