The GUI main Method
Home ] Up ] The Single Thread Rule ] [ The GUI main Method ]

 

 

Of late, it has become much more important to require programmers to write their main entry points for a Swing GUI application in the following way:

package swingThreads;

import java.awt.EventQueue;
import javax.swing.JFrame;

/**
 * An example of how a typical main entry point should
 * be coded for a Swing GUI application
 */
public class SwingMain
{
  /**
   * Main entry point
   */
  public static void main(String[] args)
  {
    EventQueue.invokeLater( new Runnable()
      {
        public void run()
        {
          JFrame frame = new JFrame("My GUI Application Frame");
          frame.setBounds(200, 200, 500, 300);
          frame.setVisible(true);
        }
      }
    );
  } 
}

One reason for this is the rapid increase in the number of truly multiprocessor machines, even at the low end of the PC market (Core Duo, etc.).  These multiple processors turn multi-threading into true multi-processing, and enormously increase the possibility of race conditions.

By writing the main entry point in this way, we can ensure that the changes to the relevant GUI objects are made exclusively in the Event Dispatch Thread, and so are appropriately serialized.

 

The page was last updated February 19, 2008