Is the spring TransactionTemplate and SimpleJdbcTemplate thread-safe?

The SimpleJdbcTemplate just wraps a JdbcTemplate, so it's thread-safe, as is the TransactionTemplate.


Actualy not. See source code for proof. At minimum TransactionTemplate has non final member transactionManager that may be not visible to already created threads. Moreover it derives all non final and publicaly mutable members from DefaultTransactionDefinition.

In reality dynamic containers (like OSGI) under load you can get NPE on usage of transaction manager inside TransactionTemplate. Especialy if you create TransactionTemplate itself (not by Spring context). It is because working threads (e.g. web request processors) already created and warm (has own thread bound CPU cache). When new TransactionTemplate is created in init thread there are no memory barrier executed to flush thread bound (or CPU core bound) cache. In very rare cases members of newly created TransactionTemplate's may be not visible to 'old' threads.

We are hit by analogios (not exactly with TransactionTemplate but with RetryTemplate) error on production after hot update of running web service. Need to say that we are not see such error in case of Spring Context created instances, may be because of global sync performed on context initialization.

Nearly all Spring template classes are mutable and has no explicit synchronization inside. Why documentation say that it is thread save I don't understand.

You may partialy protect themself by making final the field in own class that contains reference to *Template because of that statement in JMM (see attached link): "In addition, the visible values for any other object or array referenced by those final fields will be at least as up-to-date as the final fields."

In that case if you are not change state of *Template instance it is "thread safe". Not by class design itself but by specific usage and JMM properties.

See that question and java memory model on final .