所以我設法添加使用FutureTask
連接超時。
我已創建一個實現Callable
接口的類和在call()
方法我把連接邏輯:
public class CallableSession implements Callable<Session> {
private final String url;
private final String user;
private final String password;
private final String workspace;
public CallableSession(String url, String user, String password, String workspace) {
this.url = url;
this.user = user;
this.password = password;
this.workspace = workspace;
}
@Override
public Session call() throws Exception {
Repository repository = JcrUtils.getRepository(url);
SimpleCredentials credentials = new SimpleCredentials(user, password.toCharArray());
Session session = repository.login(credentials, workspace);
return session;
}
接着,在內部getSession()
函數I創建FutureTask
我的連接器類,執行,並把有一個連接超時:
public Session getSession() {
if (session == null) {
try {
CallableSession cs = new CallableSession(url, user, password, workspace);
FutureTask<Session> future = new FutureTask<Session>(cs);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(future);
session = future.get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
return session;
}