Here is the code I've stumbled 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 it is the only field in the class.
It seems to me that synchronization is not needed here because value stored in ThreadLocal is associated with particular thread and thus it's not a shared state. In addition I think it impacts performance as currentTransactionContext itself is shared and only one thread is allowed to enter the block while many can do it in parallel without impacting correctness.
Is the synchronization needed here?
currentTransactionContext.initialValue
(or even the getter) doesn't have a shared state and then you should be fine with removing the synchronisation. – Triparted