• Post Reply Bookmark Topic Watch Topic
  • New Topic

ThreadLocal synchronisation

 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hopefully a simple one...

I have a static class member that is an instance of java.lang.ThreadLocal.

Do I need to synchronise on the instance of ThreadLocal when calling set() and get() on it?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I don't see a clear statement of this in the docs, but I would think that the whole point of ThreadLocal is to be called from different threads. It had better be designed to do this in a thread-safe manner. Expecting the user to do this would be very poor design, I think. Not that Sun isn't capable of such errors. But this is pretty fundamental to what the class is supposed to do, and it would be a major bug in the class if they didn't get it right.

Now if you use the ThreadLocal to access other data that is shared between threads, that code probably still needs synchronization (or other form of concurrency protection). But the get() and set() methods themselves will not. You can see this in the example code in the JDK 5 ThreadLocal API. The initialValue() is synchronized because it needs to access nextSerialNum, which is shared across threads. But the get() method needs no synchronization.

If you look at the equivalent docs for the just-released JDK 6, be aware that there's a bug in the documentation there. And they don't use synchronization anymore in the example because they instead rely on AtomicLong to provide thread-safe access to the shared data. But the same principle is at work: the get() method needs no special thread protection; only the code that accesses the shared mutable data in the static uniqueId field needs protection.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!