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

标签 java timer jboss timertask try-catch-finally

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

相关文章:

javascript - 如何创建一个在 keyup 上启动的 jQuery 计时器

java - 如何在2个定时器之间互换?在 Java 图形用户界面中

mysql - 谁能详细指导如何使用 SSL 加密通过 Wildfly 10 应用服务器连接到 AWS RDS MySql 实例

jakarta-ee - Wildfly、WAR 和虚拟主机

java - 在 Wildfly16 上部署 Spring 应用程序时出现错误(从 Wildfly8 迁移到 16)

java - 未找到 void org.opencv.core.Core.rotate_0 的实现

java - 从小程序调用 dll 方法

c# - System.Timers.Timer 仅提供每秒最多 64 帧

java - 是否有约束语法的 Java 实现?

java - 使用不同类型的循环获得相同的结果