• Post Reply Bookmark Topic Watch Topic
  • New Topic

Under the hood ThreadLocal

 
Chandra shekar M
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Just to share a learning, Many including me think that ThreadLocal is a map with threadId is the Key. However, that is not the case, instead the keys are the threadLocal instances itself and the values will be there states and this map gets hooked up to threadId. For example


Now, when a thread executes this code, then, it will have two objects in its map

a,(Name,A) and b,(Name,B). Unlike, what is a common assumption that it will maintain a Map based on thread ID, say
(t1,a) then it would have replace the value with (t1,b) which is not the case.

Thanks,
Chandra
 
Henry Wong
author
Sheriff
Posts: 22528
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chandra shekar M wrote:Just to share a learning, Many including me think that ThreadLocal is a map with threadId is the Key. However, that is not the case ...


Agreed. If a ThreadLocal was simply a configured map, then it wouldn't be that much of a value-add. In reality, the data (value) is actually stored in the Thread object, and no synchronization is needed since each thread will only access its Thread object. IMO, it is just easier to envision it as implemented as a map.

Also, to prevent a memory leak. The ThreadLocal is referenced by the Thread object in a weakly fashion. So, when your application no longer references the ThreadLocal, the Garbage Collector will collect it, along with the data, from the Thread object.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!