What is the advantage of ‘SwingUtilities.invokeLater()’ method?

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật