我想检查我用来获取连接的jdbc代码是否是线程安全的:
环境:
Database - MS SQL Server 2005 Express Edition
Driver Class Name - com.microsoft.sqlserver.jdbc.SQLServerDriver
JDBC Jar: sqljdbc4.jar (downloaded from Microsoft website)
Application Server - Apache Tomcat 7.0
以下是context.xml文件中resource元素下的参数:
name="jdbc/xyzResourceName"
auth="Container"
type="javax.sql.DataSource"
username="someUserName"
password="somePassword"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://someHost;instanceName=someInstance;schema=someSchema;DatabaseName=someDB;"
maxActive="8"
maxIdle="4"
我使用名为HMDataService的单例并使用其静态方法执行一些CRUD操作。这是HMDataService类:
公共类HMDataService {
private static HMDataService instance = null;
private static **DataSource ds** = null;
protected HMDataService() {
// Exists only to defeat instantiation.
}
public static HMDataService getInstance() {
if (instance == null) {
instance = new HMDataService();
Context ctx;
try {
// Context lookup hardcoded only for simplicity
ctx = new InitialContext();
ctx = (Context) ctx.lookup("java:comp/env");
**ds = (DataSource) ctx.lookup("jdbc/xyzResourceName");**
} catch (NamingException e) {
log.error("Some Problem To Log", e);
}
}
return instance;
}
public static void someInsertOperation(String insertRecord) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
**connection = ds.getConnection();**
preparedStatement = connection.prepareStatement("Some SQL Here");
preparedStatement.setString(1, insertRecord);
preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error("Some Error Here", e);
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
这个HMDataService及其方法someInsertOperation将由来自servlet或jsp的任意数量的线程随机调用。 调用它的示例代码如下:
HMDataService.getInstance().someInsertOperation("Some Record To Insert");
我想知道这是否是线程安全的?我已经在线检查了Microsoft网站上的SQLServerDriver文档,但是我无法获得datasource.getConnection()是否是线程安全的任何信息。我知道线程安全特定于特定的JDBC驱动程序实现。但是,我不知道它是否适用于MS SQL Server的JDBC驱动程序的这种特定实现。