示例:将连接与并行配合使用
Runnable 或 Callable 可利用其创建组件通过使用 java:comp 资源引用获取的连接。
有关资源引用的更多信息,请参阅“引用”主题。以下是正确使用连接的任务的示例:
class GoodTask implements Callable<Object>
{
DataSource ds;
public Task() throws NamingException
{
// Cache a connection factory or datasource
// as class instance data.
InitialContext ic = new InitialContext();
// It is assumed that the created Java EE component has this
// resource reference defined in its deployment descriptor.
ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource");
}
// When the asynchronous bean method is called, get a connection,
// use it, then close it.
public Object call() throws SQLException
{
try (Connection c = ds.getConnection()) {
// Use the connection now.
return someResult;
}
}
}
以下是错误使用连接的任务的示例:
class BadTask implements Callable<Object>
{
DataSource ds;
// Do not do this. You cannot cache connections across method calls.
Connection c;
public BadTask() throws NamingException, SQLException
{
// Cache a connection factory or datasource as
// class instance data.
InitialContext ic = new InitialContext();
ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource");
// Here, you broke the rules.
c = ds.getConnection();
}
// Now when the method is called, illegally use the cached connection
// and you likely see J2C related exceptions at run time.
public Object call()
{
// Use the connection now.
return someResult;
}
}