6

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?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

1 Answers1

1

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
  }
});
tmarwen
  • 15,750
  • 5
  • 43
  • 62
  • not this is not good idea, EDT waitng until whatever from ClassPathXmlApplicationContext is loaded, invokeLater is designated to notify methods implemented in Swing APIs, methods in those APIs, – mKorbel Mar 04 '15 at 15:26
  • That may be a shortcut yes and not an ultimate solution. – tmarwen Mar 04 '15 at 15:58