Is it necessary to synchronize operations on ThreadLocal?

Here is the code I came across:

class TransactionContextHolder { private static final ThreadLocal<TransactionContext> currentTransactionContext = new NamedInheritableThreadLocal<TransactionContext>( "Test Transaction Context"); static TransactionContext getCurrentTransactionContext() { return currentTransactionContext.get(); } static void setCurrentTransactionContext(TransactionContext transactionContext) { currentTransactionContext.set(transactionContext); } static TransactionContext removeCurrentTransactionContext() { synchronized (currentTransactionContext) { TransactionContext transactionContext = currentTransactionContext.get(); currentTransactionContext.remove(); return transactionContext; } } 

}

The currentTransactionContext field is of type ThreadLocal and is the only field in the class.

It seems to me that synchronization is not needed here, because the value stored in ThreadLocal is associated with a specific thread and, therefore, is not a general state. In addition, I think this affects performance, since currentTransactionContext is by itself, and only one thread can enter a block, while many can do it in parallel without affecting the correctness.

Is synchronization required here?

+6
source share
1 answer

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 .)

+6
source

Source: https://habr.com/ru/post/1013507/


All Articles