Case of study: I have a program with some model classes and some GUI classes in Swing where I use several threads in both of them which run an infinite loop with different sleep intervals for each runnable. two of model threads run a very critical job in which if the delay rises from 40ms to 60ms will not work correctly anymore so they are extremely critical.
But I have hundreds of components in GUI that must be updated in less than a second or more frequently. These components can't be updated with observer design pattern because they don't reflect only the changes in the model. they should calculate something such as remaining time.
Problem
- I think that it will not be efficient to use hundreds of
Runnable
s invoked withSwingUtilities.invokeLater(runnable)
to update all GUI components. Because the context switch will have an enormous side-effects. So I'm going to avoid it. Should I really avoid creating all those runnables orinvokeLater()
orswing timer
doesn't run them as a thread and has an optimizing method even with all theThread.sleep(500)
among them ? - For solving the above problem I decided to create an Interface SwingUpdatable with an update method. And create a SingleTonSwingUpdater which is run evry 500ms and run all the update methods of the classes registered with it. The observer design pattern made me to think about this idea. But I'm afraid that it will be an anti-pattern. And I'm not sure if it will reduce the flexiblity of the program.
- What if I use swing Timer. It surely can't understand that if the TimerTasks all should be run in 500ms time interval so there shouldn't be a new thread for them and it's enough to do a loop on the runnables and execute them one after another.
- Does Java have a built-in solution for this problem or is there a design pattern I can use or I should rely on my solution that at the first looks so dirty?
SwingUtilities.invokeLater(runnable) adds runnable in a queue and then GUI thread executes them one at a time, so context switching is minimal. Avoid using Thread.sleep() in jobs running on GUI thread, use Swing timer instead.
The proposed "solution" adds latency to the data visualization, and has no benefits. Be careful to add solutions to the problems you do not fully understand. Human intuition works badly inside computer.
Swing's timer manages queue of timed jobs and passes them to the GUI thread when the delay expires. This is quite efficient approach.
What problem are you talking about? Hundreds events per second is not so much, standard approaches should work. If they do not, probably they are misused.