0

I'm reading B. Goetz Java Concurrency in practice and now I'm at the section about how ThreadLocal works. I used to thinking about it as a Map-like structure, but he said that

Conceptually, you can think of a ThreadLocal as holding a Map that stores the thread-specific values, though this is not how it is actually implemented. The thread-specific values are stored in the Thread object itself; when the thread terminates, the thread-specific values can be garbage collected.

what does he mean? How can I store a thread-specific value in a thread?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    [How is Java's ThreadLocal implemented under the hood?](http://stackoverflow.com/questions/1202444/how-is-javas-threadlocal-implemented-under-the-hood) – Mick Mnemonic Dec 29 '15 at 07:11

1 Answers1

1

The issue is, if it was map of threads to values in the ThreadLocal object, the values would be never garbage collected as the ThreadLocal object is never destroyed.

So it's basically the opposite - Thread object contains the map of ThreadLocal keys mapped to its thread specific values. This way the full map is garbage collected once thread finishes.

There are few other optimizations, it actually uses direct ThreadLocalMap implementation instead of implementing Map interface, uses incremental hash code and things like that, but basically the concept is as above.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43