Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer ActionListener operation in java

I am relatively new to java and was curious about how ActionListeners work. Say I have an action listener for a timer implemented as follows:

class TimerActionListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //perform some operation
    }
}

What will happen if the timer is set to run faster than the code in my actionlistener class can execute. Does the code finish executing and ignore new requests until it is done (like an interrupt). Or does the new call to actionlistener take priority over the current instance - such that the code will never complete?

like image 766
Ben Avatar asked Dec 13 '22 08:12

Ben


1 Answers

The timer's timing is done in thread distinct from the event dispatch thread (or EDT) which is the thread that runs the code in the ActionListener. So even if the actionPerformed code is slow, the timer will keep on firing regardless and will queue its actionPerformed code on the event queue which will likely get backed up and the event thread will get clogged and the application will be unresponsive or poorly responsive.

A take-home point is to avoid calling any code that takes a bit of time on the event thread as it will make the GUI unresponsive. Consider using a SwingWorker for cases like this.

Edit: Please see trashgod's comment below for the win!

like image 65
Hovercraft Full Of Eels Avatar answered Dec 14 '22 22:12

Hovercraft Full Of Eels