情况是,我必须确保在尝试 getConnection 时只创建一个 RecoveryThread,如果在 PrimaryData Source 上的 getConnection 上失败,我的代码是:
public Connection getConnection() throws SQLException {
if (isFailedOver()) {
try {
return failoverDataSource.getConnection();
} catch (SQLException e) {
throwBigError();
}
}
Connection connection = null;
try {
connection = dataSource.getConnection();
return connection;
}
catch (SQLException unexpected) {
return requestFailover();
}
}
private Connection requestFailover() throws SQLException {
this.dbFailoverMutex.requestFailover();
DBFailoverRecoveryService recoveryService = new DBFailoverRecoveryService(this.dbFailoverMutex,this.dataSource);
Thread recoveryServiceThread = new Thread(recoveryService, "DBFailover Recovery Service");
recoveryServiceThread.start();
try {
return failoverDataSource.getConnection();
} catch (SQLException e) {
throwBigError();
}
return null;
}
如果有两个不同的线程试图获取连接,这可能会最终调用 requestFailover() 方法两次,当它被调用两次时,这将最终创建两个 recoveryService 线程,我能做些什么来确保永远不会发生?
在此先感谢您的帮助。