我们有以下事务,它在运行时发送心跳。然而,在某些情况下,心跳计时器永远不会停止,即使事务没有运行,系统也会不断发送心跳。我们在这里做错了什么吗?有没有更可靠的方法来停止心跳计时器(除了停止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
}
}
}
最佳答案
你的finally block 需要属于outer try,而不是inner try。如果timer.schedule失败,那么你的finally block 永远不会被执行。像这样的东西:
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();
}
}
关于java - 事务中未到达finally{timer.cancel();},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336125/