Is Swing thread-safe in Java?


No, Java Swing components are not thread-safe in Java.

Why Swing Components are not thread-safe

  • One of the main reason for Java Swing is not thread-safe is to simplify the task of extending its components.
  • Another reason for the Java Swing is not thread-safe due to the overhead involved in obtaining and releasing locks and restoring the state.
  • Some of the Java Swing component methods will support multi-threaded access like repaint(), revalidate(), and invalidate() methods of JComponent class.

Event Dispatch Thread (EDT)

The Java Swing components can only be accessed from the Event Dispatch Thread (EDTonce 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.

Example

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

raja
raja

e

Updated on: 07-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements