Question

We have the following transaction that sends a heartbeat while it is a running. However in certain situations the heartbeat timer never stops, and the system keeps sending heartbeats even if the transaction is not running. Are we doing something incorrectly here? Is there a more sure shot way of stopping the heart beat timer (other than stopping 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   
            }    
        }

    }
Was it helpful?

Solution

You finally block need to belong to the outer try, not to the inner try. If timer.schedule fails then your finally block is never executed. Something like:

    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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top