In general, it is difficult to guarantee thread safety guarantees, given only a small fragment of the program, since threadafety is a property of the entire program, and synchronized
can coordinate behavior in many different parts of the program.
For example: maybe there is still some piece of code somewhere else that uses crazy unsafe reflection to try and check and / or mutate the guts of ThreadLocal, and therefore it will break if you mutate ThreadLocal without blocking?
Actually, however, you are absolutely right: there has never been any reason to synchronize an instance of ThreadLocal, except perhaps inside its initialValue
method. ThreadLocal itself is a thread safety mechanism, and it manages its thread safety better than you could get by clicking on synchronized
anyway.
(hint for Margaret Bloom to indicate the case of initialValue
.)
ruakh source share