5

For the below sample GUI program using javax.swing,

public class UnResponsiveUI extends JFrame{


    private boolean stop = false;
    private JTextField tfCount;
    private int count = 1;

    /* Constructor to setup the GUI components */
    public UnResponsiveUI(){
        Container cp = this.getContentPane();
        cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        cp.add(new JLabel("Counter"));
        tfCount = new JTextField(count + "", 10);
        tfCount.setEditable(false);
        cp.add(tfCount);

        JButton btnStart = new JButton("Start Counting");
        cp.add(btnStart);
        btnStart.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                stop = false;
                for (int i = 0; i < 100000; ++i) {
                   if (stop) break;  // check if STOP button has been pushed,
                                     //  which changes the stop flag to true
                   tfCount.setText(count + "");
                   ++count;
                }
            }
        });

        JButton btnStop = new JButton("Stop Counting");
        cp.add(btnStop);
        btnStop.addActionListener(new ActionListener(){
            @Override
             public void actionPerformed(ActionEvent evt) {
                stop = true;  // set the stop flag
             }
        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Counter");
        setSize(300, 120);
        setVisible(true);
    }

    public static void main(String[] args){
        /*SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new UnResponsiveUI();  // Let the constructor do the job
             }
        });*/

        /* new UnResponsiveUI(); */ 

        System.out.println("main thread exits");

    }

}

In first scenario, After debugging the constructor invoked from main() as new UnResponsiveUI();, Following is the observation wrt number of threads get launched:

1. The main() method starts in the "main" thread.

2. A new thread "AWT-Windows" (Daemon thread) is started when we step-into the constructor "new UnresponsiveUI()" (because of the "extends JFrame").

3. After executing "setVisible(true)", another two threads are created - "AWT-Shutdown" and "AWT-EventQueue-0" (i.e., the EDT).

4. The "main" thread exits after the main() method completes. A new thread called "DestroyJavaVM" is created.

5. At this point, there are 4 threads running - "AWT-Windows", "AWT-Shutdown" and "AWT-EventQueue-0 (EDT)" and "DestroyJavaVM".

6. Clicking the START button invokes the actionPerformed() in the EDT.

In second scenario, After debugging the constructor from main() invoked as,

SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new UnResponsiveUI();  // Let the constructor do the job
             }
        });

Following is observation wrt number of threads get launched but at different time instances:

1. The main() method is started in the "main" thread.

2. The JRE's windowing subsystem, via SwingUtilities.invokeLater(), starts 3 threads at a time: "AWT-Windows" (daemon thread), "AWT-Shutdown" and "AWT-EventQueue-0". The "AWT-EventQueue-0" is known as the Event-Dispatching Thread (EDT), which is the one and only thread responsible for handling all the events (such as clicking of buttons) and refreshing the display to ensure thread safety in GUI operations and manipulating GUI components.

3. Then we step-into the constructor UnresponsiveUI()to run on the Event-Dispatching thread (created via invokeLater()), after all the existing events have been processed.

4. The "main" thread exits after the main() method completes.

5. A new thread called "DestroyJavaVM" is created.

So, In above two scenarios, The total number of threads getting created are same, but at different time instance and run GUI constructor on same EDT.

From this query, i learnt that: "If you didn't use invokeLater and instead you just updated the ui directly you might have a race condition and undefined behavior could occur."

My question:

What is the advantage of using SwingUtilities.invokeLater() method? Because in second scenario, launching EDT before stepping-into constructor did not add any value.

2

Using SwingUtilities.invokeLater() is not merely advantageous, it's essential, but to understand why you need to understand Swing's threading model.

Updates to the GUI, via Swing, must occur on the Event Dispatch Thread (EDT), and code that does anything else (e.g. accessing some resource such as a database) should use one or more other threads.

invokeLater() enables these other threads to update the GUI with their results, in the EDT, e.g. showing the result of a database query.

invokeLater() is named this way to make it obvious that it is asynchronous in invoking the Runnable object you give to it, since the EDT may be busy at the time - it's not that you explicitly want it to happen later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.