gpt4 book ai didi

java - 事务中未到达finally{timer.cancel();}

转载 作者:行者123 更新时间:2023-12-01 14:01:13 25 4
gpt4 key购买 nike

我们有以下事务,它在运行时发送心跳。然而,在某些情况下,心跳计时器永远不会停止,即使事务没有运行,系统也会不断发送心跳。我们在这里做错了什么吗?有没有更可靠的方法来停止心跳计时器(除了停止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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com