java - 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());     } }   output  =============  ++ string3  ++ string3 

see set method in source code, specified thread,its threadlocalmap can hold on 1 map entry? sample shows, map.set(this, value); here "this" var "threadlocal", "string3" override previous value. mistake this?

public void set(t value) {         thread t = thread.currentthread();         threadlocalmap map = getmap(t);         if (map != null)             map.set(this, value);// here "this" var "threadlocal"         else             createmap(t, value);     } 

threadlocal local member/variable of current thread; each thread gets 1 value.

at same time there no restriction on type of value being set, in example setting string, same way can instance of class, collection.

when want values available code put them in collection(list), or custom type collects values want.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -