0

I am developing a Java application and I am at the phase of writing the GUI code. For some reason I am getting crashes on the app with crash reports (not just errors on netbeans console). I wonder if there are problems with the way I am handling events as the report often says AWT dispatch thread crashed.

Should I be creating a new thread to handle the different events firing from GUI ?

For example by making use of :

Executors.newCachedThreadPool().execute(new Runnable() {
                    public void run() {}});

Is it possible that something like that fix the crashes? Would it have negative impact on application performance ?

Giannis
  • 5,286
  • 15
  • 58
  • 113

2 Answers2

1

You are probably accessing Swing from multiple threads. Neither AWT nor Swing are thread safe. Consider using the SwingWorker class in order to ensure that it is not accessed outside of the Event Dispatch Thread.

For more information, here's another answer I have given about SwingWorker.

Community
  • 1
  • 1
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • I believe I am using SwingUtilities.invokeLater(new Runnable() { public void run() {} . I will make sure I don't miss that somewhere. Is that what you mean? also, what about the Executors showed in question. Should I use that too ? – Giannis Mar 31 '12 at 11:31
  • @latusaki, `Executors` apparently implement thread pools, from which it is unsafe to manipulate the GUI. I recommend `SwingWorker` because it provides a way for your concurrent algorithm and the GUI manipulation code to interact. – Matheus Moreira Mar 31 '12 at 11:39
  • 1
    Ok thanks for that. Just to make things clear. Operations that manipulate/change the GUI should be done using SwingWorker. If one operation is launched by a GUI event, but will not change something on GUI I can use Executor. Also : changing the model directly is considered interacting with Swing ? for example changing the document of a JTextArea. – Giannis Mar 31 '12 at 11:51
  • @latusaki, Yes, you are right. Event handlers can start as many threads as needed. You just can't update the GUI in them. Changing models are likely to trigger events which trigger GUI updates, so you probably can't do it from another thread. – Matheus Moreira Mar 31 '12 at 12:39
1

Make sure all your method calls that update the GUI from different threads than the GUI thread are forwarded to the GUI thread using SwingUtilities.invokeLater. Other threads should never change the GUI directly.

Tudor
  • 61,523
  • 12
  • 102
  • 142