Swing requires to run from within Event Dispatch Thread (EDT). How to ensure this in Spring context?
In some tutorials, like this one, swing components are just instantiated like normal beans. Is this ok?
As you have already guessed, it would be safer to run your Swing code within the Event Dispatching Thread aka EDT because most of the Swing components are not thread safe. Here is what stated in Oracle docs:
Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors.
So you should be safe to go if your initialiaze your Spring ApplicationContext
whithin the EDT thread so that your components get initialized and run in the same thread:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ClassPathXmlApplicationContext( "your-application-context.xml" ); // pay attention to context so that it is not left open
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With