Is Swing Thread Safe in Java?



No, Java Swing components are not thread-safe in Java. This means that whenever Swing components should be accessed or changed, it is done mostly by using a single thread, the EDT.

Why Swing Components are not thread-safe

One of the main reasons Java Swing is not thread-safe is to simplify the task of extending its components. Another reason for that Java Swing is not thread-safe due to the overhead involved in obtaining and releasing locks and restoring the state.

Below are some methods given by Swing for safe operation with its UI:

  • SwingUtilities.invokeLater(): In most cases, this is calling for a Runnable to be executed on the EDT; the Swing framework generally recommends this way of updating its components with information from a background thread.
  • javax.swing.Timer: For operations that must be executed repeatedly at fixed intervals on the EDT, the Timer class offers a useful solution.
  • SwingUtilities.invokeAndWait(): Like invokeLater(), this will block the calling thread until the Runnable has finished execution on the EDT. Use with care, as it can cause deadlocks if invoked from the EDT itself.

Some of the Java Swing component methods will support multi-threaded access, like repaint(), revalidate(), and invalidate() methods of the JComponent class.

Check if EDT is There!

Below is the syntax to check if EDT is present or not:

if (SwingUtilities.isEventDispatchThread()) {
    System.out.println("Running on the EDT!");
} else {
    System.out.println("Not on the EDT!");
}

Event Dispatch Thread (EDT)

The Java Swing components can only be accessed from the Event Dispatch Thread (EDT)once a component is available for painting onscreen. The EDT thread is the thread that invokes callback methods such as paint() and update() in addition to event handler methods defined in Event Listener interfaces.

Only thread-safe methods can be safely invoked from any thread. Since most of the Swing object methods are not thread-safe, they can be invoked from a single thread, the EDT.

Consequences of Ignoring the EDT

The following are the consequences of ignoring the EDT in Java:

  • Visual Problems: Some areas might not display properly, causing flicker, tearing, or missing images.
  • Race Conditions: The code behavior becomes very unpredictable when multiple threads try to write to the same place at the same time.
  • Deadlocks: In more complex situations, the absence of proper synchronization leads to deadlocks that freeze the application.
  • Application Crashes: In some very rare cases, an application would crash because of ignoring the single-thread rule.

Example of Swing EDT

Below is an example to demonstrate the Swing EDT to delay a thread in Java:

import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
public class EDTTest extends JPanel implements ActionListener {
   private static EDTTest myPanel;
   private static JFrame myFrame;
   public EDTTest() {
      super();
   }
   public Dimension getPreferredSize() {
      return new Dimension(500,425);
   }
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
   private static void createAndShowGUI() {
      myFrame = new JFrame("EDT Program");
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setLocationRelativeTo(null);
      myPanel = new EDTTest();
      myFrame.add(myPanel);
      initMenu();
      myFrame.setVisible(true);
   }
   private static void initMenu() {
      JMenuBar menuBar = new JMenuBar();
      myFrame.setJMenuBar(menuBar);
      JMenu file = new JMenu("File");
      JMenuItem quit = new JMenuItem("Quit");
      quit.addActionListener(myPanel);
      file.add(quit);
      menuBar.add(file);
   }
   public void actionPerformed(ActionEvent ae) {
      String choice = ae.getActionCommand();
      if (choice.equals("Quit")) {
         System.exit(0);
      }
   }
}

In the above example, the SwingUtilities.invokeLater() method will delay the GUI creation task until the initial thread's tasks have been completed, then make sure the GUI creation takes place inside the EDT.

Output

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-04-23T17:17:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements