Swing Is Non Thread-Safe Inward Coffee - What Does It Mean? Effect Dispatcher, Swingworker, Multithreading Together With Best Practices

Advertisement

Masukkan script iklan 970x90px

Swing Is Non Thread-Safe Inward Coffee - What Does It Mean? Effect Dispatcher, Swingworker, Multithreading Together With Best Practices

Sabtu, 16 Januari 2021

Couple of my reader enquire question, what does it hateful past times Swing is non thread-safe together with How does it touching on coding inwards Swing GUI application? This post is an endeavour to aid those readers together with several other programmers to sympathize Swing together with thread-safety inwards a fight to a greater extent than detailed way. To proceed it simple, let's revise what does it hateful past times beingness thread-safe? We say an object is thread-safe, if nosotros tin telephone telephone it's method, which tin alter it's state, from multiple thread at same time. To give y'all an example, java.lang.String is a thread-safe class, which agency y'all tin telephone telephone whatever method e.g. substring(), toUpperCase() or toLowerCase() from multiple threads. By the way, String is thread-safe because it's immutable. Let's come upwards dorsum to Swing now, Core business office of Swing is made upwards of dissimilar GUI gene e.g. JLable, JPanel, JCombobox etc. All these components are not thread-safe, which agency y'all tin non telephone telephone methods of this components e.g. JLable.setText("new title") from whatever thread, other than Event Dispatcher Thread(EDT)

In i word, Since Swing is non thread-safe, y'all tin non update Swing components from whatever random thread, they are e'er updated using Event Dispatcher thread. This is inwards fact i of the most popular Java Swing Interview Question, amongst lot's of interesting follow-up e.g. 

If Swing is non thread-safe than how create y'all update components from other thread? together with which methods of Swing API are thread-safe? etc. We volition run into respond of this enquiry inwards side past times side section.



How to update Swing Component from dissimilar thread

blocking method together with blocks until GUI is updated, spell invokeLater() is an asynchronous telephone telephone together with doesn't await for GUI to endure updated. By the way, both of these method brand certain that Swing GUI components are updated inwards EDT thread only. Both of these method takes a Runnable object, which contains code to update GUI, every bit shown below :

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    JLable.setText("Update Title");
  }
}

to acquire to a greater extent than most both of these methods together with How to purpose them, See when to purpose InvokeAndWait together with InvokeLater inwards Java.

Couple of times, Interviewer too enquire about, how create y'all find, if a special thread is Event Dispatcher thread or not? Well, if y'all are familiar amongst Swing API, they y'all may know that SwingUtilities provides isEventDispatchThread() method, which tin endure used to notice out if electrical flow thread is Event Dispatcher thread or not. Another follow-up enquiry is Why Swing is non thread-safe inwards Java? Well, this is on similar lines similar why multiple inheritance is non supported inwards Java or Why Java doesn’t back upwards operator overloading

It's the determination taken past times in that place designer, at that time. Since making an API thread-safe takes a lot of work, together with it's frequently based upon create goodness y'all get. Since GUI screens are to a greater extent than frequently than non updated inwards reply of user activity e.g. when user click a button, together with since events are handled inwards the same Event dispatcher thread, it's tardily to update GUI on that thread. It's really rare, when an update asking for GUI comes from a dissimilar thread e.g. may endure i time a network asking is consummate or a file is loaded. 

In such cases, y'all tin purpose either invokeAndWait(), invokeLater() or preferably SwingWorker class, which is designed to run these lengthy fourth dimension consuming chore inwards a dissever thread together with same fourth dimension managing inter thread communication betwixt worker thread together with Event dispatcher thread. 

Since EDT thread is most of import inwards Swing together with responsible for listening consequence together with updating GUI, y'all must non create whatever fourth dimension consuming chore on it, otherwise, y'all jeopardy your application to buy the farm unresponsive or frozen. Another cardinal matter to note, spell using multi-threading inwards Swing evolution is that, non solely GUI components but in that place model e.g. TableModel for JTable, must endure updated inwards Event Dispatcher thread. One of the crucial difference betwixt AWT together with Swing is that AWT components are thread-safe

Summary

Here is summary of our discussion, which is too a listing of Java Swing best practices inwards multithreading environment. When y'all purpose threads inwards Swing development, y'all jeopardy of deadlock together with frozen GUI. By next these elementary rules, y'all minimize your chances of errors.

1) Since Swing components are non thread-safe, until whatever specifics mentioned inwards Javadoc, they must endure created together with modified from AWT Event Dispatcher thread.

2) Not solely Swing components but too in that place model e.g. ListModel, TableModel must endure modified from Event Dispatcher thread.

3) AWT Event Dispatcher thread is responsible for updating GUI together with listening events, together with thus don't block them past times doing fourth dimension consuming chore there.

4) You tin purpose java.awt.EventQueue's isDispatchThread() or SwingUtilities.isEventDispatchThread() to banking corporation jibe if electrical flow thread is EDT.

5) Use SwingWorker to perform lengthy fourth dimension consuming chore inwards worker thread.
6) Use InvokeAndWait() together with invokeLater() to update GUI components from threads other than Event Dispatcher thread.

That's all on Why Swing is non thread-safe inwards Java, to a greater extent than of import what does it hateful past times Swing beingness non thread-safe. We receive got too touched base of operations on Event Dispatcher thread, SwingWorker, invokeAndWait, together with invokeLater. This is an extremely of import theme from Swing evolution together with Interview scream for of view. I receive got never seen a Java Swing Interview, without whatever enquiry from threading.

Further Reading
Java Swing (GUI) Programming: From Beginner to Expert
Mastering Java Swing - Part 1
The Complete Java MasterClass