[concurrency-interest] Bug in ThreadLocal ?

Joshua Bloch josh at bloch.us
Fri Apr 13 15:02:41 EDT 2007


This would be a bug, but I can't reproduce it.  When I run this program:

public class TlTest {
    private static ThreadLocal<Void> tl = new ThreadLocal<Void>() {
        @Override protected Void initialValue() {
            System.out.println("Hi mom");
            return null;
    public static void main(String[] args) {

It prints "Hi Mom" twice.  Can you give me a small reproducible test case?


On 4/13/07, Hanson Char <hanson.char at gmail.com> wrote:
> Hi,
> According to the javadoc of ThreadLocal#remove (in jdk1.6),
>     "If this thread-local variable is subsequently read by the current
> thread, its value will be reinitialized by invoking its initialValue method"
> So I would expect, within the same thread, a ThreadLocal#get followed by ThreadLocal#remove
> followed by ThreadLocal#get would result in ThreadLocal#initialValue being
> invoked twice.
> But this is not the case.  The last "get" did not cause the "initValue" to
> be invoked.  When I looked at the code of the "remove" and "get" method
> implementation, it seems there is a bug in that the internal "
> t.threadLocals" should be set to null when the remove method is invoked,
> but is not currently the case.
> Am I mistaken or is this a bug ?  Comment ?
> Thanks,
> Hanson Char
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20070413/827bb14c/attachment.html 

More information about the Concurrency-interest mailing list