lawrence
lawrence

Reputation: 353

ThreadLocal source code Confusion

public class App 
{
    public static void main( String[] args )
    {
        ThreadLocal<String> threadLocal = new ThreadLocal<String>();
        threadLocal.set("String1");
        threadLocal.set("String2");
        threadLocal.set("String3");

        System.out.println("==============");
        System.out.println("++ " + threadLocal.get());
        System.out.println("++ " + threadLocal.get());
    }
}


the output is 
============= 
++ String3 
++ String3

see the set method in the source code, for specified Thread,its threadlocalmap can only hold on one map entry? as the sample shows, map.set(this, value); here "this" is the var "threadLocal", so "String3" will override the previous value. Do I mistake this?

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);// here "this" is the var "threadLocal"
        else
            createMap(t, value);
    }

Upvotes: 0

Views: 188

Answers (2)

TwoThe
TwoThe

Reputation: 14269

ThreadLocal maps from Thread to value. When asking from the same thread - so with the same key - the returned value is of course the same.

This is the purpose of ThreadLocal: to deliver always the same value to a thread.

Upvotes: 1

Rizwan
Rizwan

Reputation: 2437

ThreadLocal is a local member/variable of the current thread; so each thread gets exactly one value.

At the same time there is no restriction on the type of value being set, in your example you are setting it as String, same way this can be an instance of the class, collection.

When you want all the values to be available from your code then put them together in a collection(list), or a custom type which collects all the values that you want.

Upvotes: 1

Related Questions