首页 > 解决方案 > Why Spring JdbcTemplate is thread-safe?

问题描述

I am learning how multithreading is supported by Spring. I found that Spring docs say that JdbcTemplate is thread-safe once configured. People suggest to use one instance of JdbcTemplate for the whole app as it is thread-safe (meaning there is no need to create a new instance for each class).

But when i look at the JdbcTemplate code i do not see any synchronized methods, locks or volatile variables. Also it contains a lot of instance variables. My question is how the JdbcTemplate can be thread-safe in this case?

标签: javaspringmultithreadingspring-jdbc

解决方案


这是JDBCTemplate Best Practices部分下 Spring 参考文档的片段

JdbcTemplate 类的实例是线程安全的,一旦配置。这很重要,因为这意味着您可以配置 JdbcTemplate 的单个实例,然后安全地将这个共享引用注入到多个 DAO(或存储库)中。JdbcTemplate 是有状态的,因为它维护对 DataSource 的引用,但这种状态不是会话状态。

正如文档中清楚解释的那样,您也可以在源代码中看到。这个类不持有任何会话状态。它只有配置信息。


推荐阅读