Search code examples
javaswingawtevent-dispatch-threadawt-eventqueue

How to implement idle task in Java Swing


I have a GUI app that is getting to be quite slow. I want to start introducing timing for various GUI tasks - however, many of our GUI actions trigger other actions which then "invoke later" to trigger other actions.

Eventually, it all settles down and there's nothing more to do. At this time, I want to stop a timer and report how long that GUI "action" took.

I figured the way to do this is to implement a method called invokeOnceIdle(Runnable task). The method will execute the supplied task only once the AWTEventQueue is "empty". i.e. the supplied "task" should be the last thing in the queue.

One way to do this would be is if there's a way to specify a "lowest" priority to SwingUtilities.invokeLater - but this isn't possible.

I next looked to see if I could "invokeLater" a Runnable which checks to see if the event queue is "empty" - but there's no public way to see if the event queue is actually empty.

What's the best way to do this?


Solution

  • Using your own event queue, you can easily reach that goal. Here something that I cooked up and should get you going:

    private static class MyEventQueue extends EventQueue {
    
        private Deque<Runnable> onceIdle = new LinkedList<Runnable>();
    
        public MyEventQueue() {
            Toolkit.getDefaultToolkit().getSystemEventQueue().push(this);
        }
    
        public void runOnceIdle(Runnable toRun) {
            onceIdle.addLast(toRun);
        }
    
        @Override
        protected void dispatchEvent(AWTEvent event) {
            super.dispatchEvent(event);
            if (peekEvent() == null) {
                for (Runnable toRun : onceIdle) {
                    toRun.run();
                }
                onceIdle.clear();
            }
        }
    }
    

    All you have to do is push your "Once idle" runnables to the instance of the EventQueue using runOnceIdle()