예제: 동시성으로 연결 사용
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;
}
}