Timer ActionListener statement in java

I am relatively new to java and I was curious how ActionListeners work. Let's 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 happens if the timer runs faster than the code of my actionlistener class can execute. Does the code execute and ignore new requests before it finishes (for example, interrupting). Or does a new actionlistener call take precedence over the current instance - so that the code never exits?

+4
source share
3 answers

The timer time runs on a thread other than the event dispatch (or EDT) thread, which is the thread that runs the code in the ActionListener. Thus, even if the actionPerformed code is slow, the timer will continue to fire independently and will stand in line of its actionPerformed code in the event queue, which is most likely to be copied, and the event flow will be clogged, and the application will be unresponsive or poorly responsive.

The return point is to avoid invoking any code that takes a little time in the event stream, as this will render the GUI inactive. Consider using SwingWorker for such cases.

Edit: see trashgod comment below for victory!

+8
source

Based on hovercraft and trashgod messages, it seems that timer events do not have a default queue. (that is, new timer events will be ignored until the timer event handler code finishes executing.)

+3
source

You can test it yourself by implementing something as follows:

 class TimerActionListener implements ActionListener { public static int inst = 1; public void actionPerformed(ActionEvent e) { int id = inst++; System.out.println("Executing instance: " + id); try { Thread.sleep(3000); } catch (Exception e) {} //For sleep 3 seconds System.out.println("Instance: " + id + "done! "); } } 
+2
source

All Articles