About the EDT (Java)

477 views Asked by At

I have read a number of articles on the internet about when something should run in the EDT, and when it shouldn't. But I'm still not sure I understand, so I'd like to ask a few question about this:

  1. What pieces of code are going to run by default inside the EDT?

  2. What pieces of code are going to be run be default outside the EDT?

  3. When should I use InvokeLater() so something that by default would run outside the EDT, will run inside it?

  4. When should I prevent a piece of code from running (by default) inside the EDT, by creating a new thread and putting that code inside it?

Thanks

2

There are 2 answers

2
dehlen On

First of all thank you so much for editing and formatting your question very well. It helps a lot when answering your question.

Also i have to admit i am not 100% sure about my answers, so guys: feel free to correct me if i am wrong.

  1. Everything which changes your graphical user interface.

  2. Not quite sure about that.

  3. If you need to update your gui with the time intensive calculations. For example if you want to show the numbers from 0to 100000000 in a JLabel.

  4. Everything which would block your gui from user interaction because it takes a lot of time, for example some calculations with a lot of datasets.. But you need to make sure to access values only from one thread or to synchronize the threads with volatile and
    synchronize...

10
JB Nizet On
  1. All the code executed by an event listener.
  2. The code in your main method, the code executed inside a thread that you explicitely started, or that has been started by the usage of a Timer or SwingWorker.
  3. When creating a Swing GUI in your main method. Or when you want to interact with a Swing component (or its model) from inside a background thread.
  4. When this piece of code is blocking (like long IO) or is taking more than a few milliseconds to execute. All the code executed from inside the EDT prevent this thread from doing its main job: repainting the GUI and reacting to events.