javaswingawtevent-dispatch-thread

java- not using event dispatching thread?


First of all, I know there are multiple questions out there on this topic, but none of them answers what I want to know.

During going through some questions, I came across a advice that we should always use EDT to update our GUI.

My questions are,

  1. When should I use it? One example please.
  2. What will happen if I don't use it? One example please. Code not required.

Solution

    1. The Event Dispatching Thread is the thread where all Swing-related work should happen. As you've seen, you can sometimes get away with not explicitly using it to update your UI, although this is considered bad form.

    2. The EDT is responsible for your Swing UI. It handles mouse clicks, events, callbacks, window drawing, etc. Every time an ActionListener is called, it's called by the EDT.

    3. Every time you register a listener with Swing, you're using the EDT, even if you don't explicitly mention it.

      For example:

      JButton button = new JButton();
      button.addActionListener(e -> System.out.println("Clicked!"));
      

      Even though you don't mention the EDT, you're still using it. The listener is called from the EDT when the button is clicked.

      Another way to use the EDT is with SwingUtilities.invokeLater(). You would use this when you need to update the UI from a thread that's not the EDT. Swing is thread unsafe, which means that it's not safe to update the UI from outside the EDT. Even if things work on your computer, it's not guaranteed to always work. You can read a little more on a relevant question here.

    4. As I've said, not using the EDT is unsafe, since Swing makes no guarantees about thread safety.

    5. If you use Swing, you're always using the EDT. But you can schedule tasks to run on the EDT with methods like invokeLater() and invokeAndWait().