tags:

views:

38

answers:

2

I have a module that sets Swing Timer to wake up after 3 minutes and I see that it is fired after less than 2 minutes. I have to mention that while waiting for the Timer, an extensive Swing activities went on and other Swing Timers, on different threads were used. Could such activity affect the Timer's timing?

A: 

This article recommands not to use a large number of swing timers. http://java.sun.com/products/jfc/tsc/articles/timer/

I hope this reading can help you.

Laurent K
A: 

Yes, it could definitely interfere.

If you have a lot of scheduled activities going on, you would likely be better off using a ScheduledThreadPoolExecutor to schedule tasks.

To make sure that the scheduled work is executed in the Swing thread, you can use a wrapper such as this one for the Runnables that you schedule:

public abstract SwingRunnable implements Runnable
{
    public final void run()
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
            public final void run()
            {
                runInSwing();
            }
        }
    }

    protected abstract void runInSwing();
}

Even better (if you know what you're doing ;-) ), you could only put the parts of your scheduled work that actually need to be executed in the Swing thread into the Swing thread. The wrapper code that I've given here will run all of your code in the Swing thread, which is the same as what you are currently doing using javax.swing.Timer.

Joe Carnahan