java - 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?
解决方案
这是JDBCTemplate Best Practices部分下 Spring 参考文档的片段
JdbcTemplate 类的实例是线程安全的,一旦配置。这很重要,因为这意味着您可以配置 JdbcTemplate 的单个实例,然后安全地将这个共享引用注入到多个 DAO(或存储库)中。JdbcTemplate 是有状态的,因为它维护对 DataSource 的引用,但这种状态不是会话状态。
正如文档中清楚解释的那样,您也可以在源代码中看到。这个类不持有任何会话状态。它只有配置信息。
推荐阅读
- ios - iOS Swift:将打印和调试打印写入文件
- javascript - 以角度形式将输入创建为数组
- capybara - 切换到无头 chrome 后如何忽略多余的空格
- javascript - 如何连接具有匹配 ID 的数组内的对象?
- django - Django 中的 STATIC_ROOT 无法正常工作
- java - java char编码长度应该总是x乘以2?
- c# - 在 EF Core 中,在断开连接的场景中插入数据与在连接的场景中插入数据有什么区别?
- javascript - 如何将 PHP 变量值传递给 Paypal 的客户端代码
- linux - linux如何获取最深的子文件夹?
- sql - 字符串中的 SQL 列值