我们有以下事务在运行时发送心跳。但是在某些情况下,心跳计时器永远不会停止,即使事务未运行,系统也会继续发送心跳。我们在这里做错了吗?有没有更确定的停止心跳计时器的射击方式(除了停止jboss)?
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Asynchronous
public void performUpdate(long requestSettingId) throws exception {
try {
// At this line a new Thread will be created
final Timer timer = new Timer();
// send the first heartbeat
workerService.sendHeartBeat(requestSettingId);
// At this line a new Thread will be created
timer.schedule(new HeartbeatTask(setting.getId()), heartBeatInterval, heartBeatInterval);
try {
//Perform update
//
} finally {
// terminate the HeartbeatTask
timer.cancel();
} catch (Exception e) {
//Notify the task owner of the exception
}
}
}
答案 0 :(得分:1)
你最后阻止需要属于外部尝试,而不是内部尝试。如果timer.schedule失败,则永远不会执行finally块。类似的东西:
public void performUpdate() throws exception {
Timer timer = null;
try {
// At this line a new Thread will be created
timer = new Timer();
try {
timer.cancel();
} catch (Exception e) {
//Notify the task owner of the exception
}
} finally {
if ( timer != null ) timer.close();
}
}