I have a simple JAVA program with gui that just increments int variable and displays its value in JLabel. I create new thread for proper(thread-safe) updating JLabel by calling inside it EventQueue.invokeLater() with Runnable class which run method simply does
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("" + number);
}
});
When i run program, as expected label's number starts to grow rapidly from 1 to about 5000 but then it starts to slow down and i'm starting to see such label's updates like 100255, 173735, 235678 and big pauses between them with blocked GUI.
But when i compile without using EventQueue.invokeLater(), just calling directly label.setText("" + number);
everything works fine and perfect and i can see how each number of my label is changing extremely fast. But of course i realize in that case my method isn't thread-safe.
What's the problem? It seems to me that EventQueue works slow or something.
Probably, the event queue is being choked up. You may want to look at coalescing the events to remove redundant entries when you are queuing event faster than they can be dequeued and actioned.
Every time an event is added to the queue, the existing events are queried to see if they merge the new event with themselves. As the queue backs up, more and more events have to be so queried, and the system gets progressively further behind. This is useful for mouse events, but in a simple (and artificial) case like this it can be detrimental.
Having said that, I vaguely recall that the GUI code is optimized to not attempt coalescing events that don't override the appropriate method, so your problem may be just a simple backlog.
Instead of calling setText
directly, you could create a custom event for setting text on a component, implement coalescing for it and use that instead so that at any given time only the most recent text is pending. If you do this and you want to set the text based on what was previously set it's better to retain the value and always set the GUI widget from that rather than recalling the GUI widget's current value with getText
. Otherwise merging is much more difficult.