When to use SwingUtilies.invokeAndWait/invokeLater - java

I read somewhere that for any thread that affects the visuals of the gui it should be ran in the EDT using SwingUtilities.invokeAndWait/invokeLater
For a basic gui, is it necessary to put something like new SwingGUI().setVisible(true); in the line of the EDT using invokeAndWait? Just to display?
Does this count?

The short answer to your question is: yes, even calling setVisible should happen on the EDT. To find out whether the current thread is the EDT, you can use the EventQueue#isDispatchThread method
Some reference links:
Multithreaded Swing Applications
Threads and Swing
Concurrency in Swing
Edit:
after reading the links I provided, it seems some of the articles on the Oracle site are outdated as in they still document you can create Swing components on another thread. There is a stackoverflow question on this which contains some nice answers and links to blogposts and articles about the 'new' policy (new as in a few years old)

Yes, if you touch a Swing object you have to do it on the EDT. In most cases you are already there, but if not, use the SwingUtilities classes. The reason for this is that the Swing classes are not multi-threaded, so you are likely to cause nasty problems if you access it on other threads. And it could be that setVisible() is doing a lot of things under the covers to make something display (like re-laying things out). Better to be safe.

Anything that is called from your
public static void main(String[] agrs) {
directly (without spawning another thread or using invokeLater) is running on the main thread.
Accessing GUI objects with the main thread while they may be being accessed (simultaneously) by the EDT (which is triggered by user input) can cause threading issues. Calling invokeLater causes tasks (runnables) to run on the EDT, preventing simultaneous access by other EDT tasks ie. button presses etc.
If you can be sure the EDT is not busy (before the first window is setVisible(true)) you can access the GUI from the main thread. If you can be sure the EDT has no reference to the component you're working on (it is out of EDT's scope) ie. before it's added to any container, you can access it from main thread without the EDT accessing it simultaneously, as the EDT has no way to reach it.

Everything that access Swing objects should do so via the Event Dispatch Thread (EDT). There is one small exception to this (which I'll mention later). The purpose of the EDT is to process any events that may occur due to IO (mouse and keyboard events). Quite a lot of the time this can mean altering the layout of your GUI. Swing was not developed to be thread-safe, meaning that that if two thread try to modify the same component at the same time then you can end up with a corrupted GUI. Since there is already one known thread to be accessing Swing components (the EDT), no other thread should attempt to modify them or even read their state.
Now, to the exceptional case when you can manipulate Swing objects outside of the EDT. Before any components have become visible it is not possible for IO to be triggering events. Therefore, the main thread can setup a Swing GUI and then set a single JFrame to be visible. Since there is now a visible frame IO events can occur and the main thread should not try to modify any more Swing components. The should only use this option to get a GUI started, and really only with toy problems.
What I'm saying is that the following is fine and won't cause problems if you're just playing around with stuff.
public static void main(String[] args) {
// create components
JFrame f = new JFrame();
...
// do layout and other bits of setup
// show gui to user
f.setVisible(true);
}

Related

Do all Swing components run on the EDT by default?

I'm new to Java and after reading many articles about threads and swing I understood that all the invocations of Swing methods should be done on the EDT because Swing is not thread safe. however, I already wrote a couple of quite long Swing applications before reading about the EDT. and all of my applications ran quite fine. So my question is were my Swing applications running on the EDT by default or were they running on a different thread and i was just lucky not to have any issues with them?
Like for example if I add a JButton to a JPanel or JFrame, or if I simply call a JTextField's Field.setText(), will these operations be running on the EDT by default or no?
and if the answer is no, then do I have to explicitly send all my Swing component's methods implementations to run on the EDT by invoking SwingUtilities.invokeLater()
Thanks
Remember objects don't live on threads, only execution of methods happens on a thread.
All action emerging (through listeners) from swing components automatically run on the EDT.
For instance a button you click, the onClicked() function will already run on the EDT so you don't need to do anything.
If you don't create any threads explicitly, your basic application will have a main thread and an EDT (and many other threads that you don't accidentally get your code executed on, until you start using extra frameworks).
The thing you have to do manually is construct the GUI on the EDT. As you can see here this can be done in your main thread as follows:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow window = new MyWindow ();
window.setVisible(true);
}
});
If you fail to use the EDT correctly. Everything will seem to work fine, but every now and then you can get very strange behavior (because two threads will be doing things instead of one).
So in summary you have to use invokeLater(), or in some exceptions invokeNow() in the following cases:
Constructing Swing components from the main thread.
Calling swing components from your personally created threads.
Calling swing components from events on threads created by frameworks.
This question contains some tools that can help you automatically detect errors (not all though).
where my Swing applications running on the EDT by default or were they running on a diffrent thread and i was just lucky not to have any issues with them?
They were mostly being ran on the EDT. All the painting and updating that Swing does by itself is on the EDT. Anything you do specifically in your code base that you know wasn't on the EDT, is the code that was not on the EDT. So these would be actions like querying the text of a JLabel, or setting the text of a JLabel, or initializing the JLabel itself.
The various listener methods that are executed by Swing which you have implemented in your code base are however executed on the EDT (as long as Swing called it, not yourself). So in these methods you can query/modify Swing components, but remember to properly transfer in and out any data you give to a Swing component or queried from a Swing component in a thread-safe manner.
Like for example if I create a JButton and add it to a JPanel or JFrame, are these operations running on the EDT by default or no?
The initialization of the objects happens on whatever thread you created them on, and so are the rest of the modifications of the Swing objects (like adding one component to another). I do not know of any Swing components whose public method implementations are wrapped in their own invokeNow() or invokeLater() call, so it's best to assume all portions of the actions happened on whatever thread you called the original methods on.
do I have to explicitly send all my Swing components and methods to run on the EDT by invokingSwingUtilities.invokeLater()
Yes, or invokeNow()
Components will be accessed from within the thread context they are called, wch leads to a problem...
All Swing components (or enough not to matter) MIST be accessed within the context of the Event Dispatching Thread once they have been added to a displayable container (attached to a native peer).
This makes Swing components NOT thread safe and you are responsible for ensuring that they are modified/accessed from the EDT correctly, the framework will NOT do it for you
Take a look at Concurrency in Swing for more details

What if I don't use SwingUtilities.invokeLater?

When I start my GUI interfaces, what can happen if I don't use invokeLater?
Does that mean all rest of the GUI paints/updates/etc. will be in the main thread?
Will calling a repaint outside of an invokeLater make all subsequent calls fall into the main thread?
Basically this:
void main()
{
JFrame jmf();
setVisible(jmf);
}
------------- VS -------------
void main()
{
SwingUtilities.invokeLater(new Runnable(){
run(){
JFrame jmf();
setVisible(jmf);
}
}
});
NOTE: In cases with small GUI, I if I don't put the invokeLater it seems to work fine. And in fact the application doesn't terminate although the last line of the main is executed.
I have read quite a few articles on why we should use it pertaining to the fact that Swing is not thread safe (it is single threaded and so on), but I really didn't read the repercussions of not calling invokeLater (partially because of my limited knowledge in Threads)
The reality is, nothing might happen or the world will end. It's next to near impossible to predicate, this is the nature of multi-threaded environments...
Unless you are doing some really dynamic setups, until the a frame is made visible it "should" be okay not to do it within the context of the EDT.
The problem comes down to the fact that different platforms are implemented differently (at the native level). For example, the original requirement for using invokeLater when starting your UI seems to have come from deadlocks on the Sun OS many years back.
I've also seen some issues with Java 7 (but my predecessors idea of the thread was weird to say the least). The general advice is, use invokeLater to create and display your UI. Run all UI code within the context of the EDT
It will also reduce the risk of you having to spend weeks trying to replicate and track down those weird anomalies (by running you all you UI code from within the EDT)
Updated based on comments from the OP
repaint makes a request to the RepaintManager, that makes decisions about what and when something should be paint. It will actually post a "paint" event directly on to the Event Queue, which is then processed by the Event Dispatching Thread, so repaint is actually on (of the few) thread safe methods...
Take a look at
Painting in AWT and Swing
Initial Threads
Will the real Swing Single Threading Rule please stand up?
Why is Swing threading model considered wrong and how should it be?
The general advice would be, you should use invokeLater because that's how the API has been designed, doing anything else is inviting problems...

Two threads writing to the same JTextArea

I'm just going through a Java course and several weeks before we went through multithreading where it was explained that when two(or more) threads work with the same object, the object has to be locked from all over threads except the one working with it.
Having a GUI I want to write some data from 2 threads to a JTextArea should I bother about locking the object when one thread writes to it or this is handled already by the JTextArea? If I should bother about it, how would I go doing this since I can not declare a Lock inside the JTextArea class definition? If I should not bother about this, does it stays the same with all swing object, if not, what are the exceptions?
For the most part, Swing is inherently not thread-safe, so you cannot do this - you must update all GUI components from the EDT by wrapping up the call in SwingUtilities.invokeLater(). For example:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.setText("Blah");
}
});
Although there are technically exceptions to this rule with a few select components, I'd still by far prefer to execute everything on the EDT unless there's a very good reason otherwise (very, very rarely the case.)
In Swing you have to update GUI components only from UI thread. So you have to schedule those updates from your threads to be executed on UI thread.
This is one example with SwingUtilities.invokeLater().

How do you use the Event Dispatch Thread?

I learned about how swing isn't thread-safe. Delving deeper, I discovered that every modification to a swing component must be done on the Event Dispatch Thread in order to prevent various issues associated with multithreading. However, the information seemed to completely stop there. There doesn't seem to be a good tutorial that explains how to do this anywhere accessible on the internet.
Patching together information from code posted in relation to other issues, it seemed that I would have to put an untidy block of code around every single swing modification in my program (like this example from my own code):
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setTitle("Frame title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(800, 480);
setLocationRelativeTo(null);
setIconImage(Toolkit.getDefaultToolkit().createImage(ClassLoader.getSystemResource("Frame icon.png")));
}
});
} catch (Exception e) {
e.printStackTrace();
}
Basically, is this right? Do I have to put that code (or the equivalent with invokeLater) around every modification to a Swing component in my code?
Also, why doesn't Swing do this automatically?
The trick is that when swing calls you it will ALWAYS be in the EDT, so you don't have to worry about it.
However if you are in a timer or an action triggered by some other external event, your main thread or any other thread you've created then yes, you have to use invokeLater or invokeAndWait.
In other words, yes swing does do "it" automatically. Needing to use invokeXx is so rare that if swing were to do it internally it would waste too much time.
Many java programmers never figure this out and it can cause some pretty nasty hard-to-find problems with drawing your GUI. I do wish swing threw an exception when you called it not using the EDT--Java would have a better reputation when it came to professional GUIs if it did because there would be less crap out there.
note that any code executed from event handlers is already run in the EDT (the Event in the acronym)
this means that for general use (while you don't mess with swingworkers and threadpools and such) you are always inside the EDT
and you can always query if you are in the EDT with SwingUtilities.isEventDispatchThread()
also note that in your code the call to invokeAndWait will fail and throw an error when you are in the EDT already
Basically, you dont draw or update the GUI from outside of the EDT.
You use SwingUtilitis.invokeLater() from another thread to ensure the GUI drawing or updating code is run on the EDT.
Not all your UI code must be part of a runnable in an invokeLater call. That is simply because a large part of your program will be run on the EDT anyway. You need to dispatch messages to the EDT only when you are on a different thread.

SwingUtilities.invokeLater() why is it needed?

Why is it necessary to put GUI update code in SwingUtilities.invokeLater()?
Why cant it be internally taken care of by Swing itself? Why does the caller have to care about how swing handles UI updates?
Swing objects are not thread safe. SwingUtilities.invokeLater() allows a task to be executed at some later point in time, as the name suggests; but more importantly, the task will be executed on the AWT event dispatch thread. When using invokeLater, the task is executed asynchronously; there's also invokeAndWait, which won't return until the task has finished executing.
Some information about the decision not to make Swing thread-safe can be found here: Multithreaded toolkits: A failed dream? [Archived]
Because GUI updates must be done in the event dispatch thread. If you're operating in a different thread, doing the update in invokeLater yanks it out of your thread and into the event thread.
More explanation here: http://www.oracle.com/technetwork/java/painting-140037.html
The smart thing to do with big updates (like repopulating a JTable from the database) on Swing is to get the underlying model, do the updates on the model in your thread, then fire off a notification using invokeLater. That keeps your gui responding to events and redrawing. If the update is going to be very extensive, you can even fire off these notifications with invokeLater at regular intervals while you're updating, like every second or two.
Swing is single-threaded. Every update to the UI must happen from the so-called EDT – the event-dispather thread which is the main GUI thread Swing (and I think AWT) uses. If you don't do this, then weird things can or will happen (though I like Windows Forms better here which just throws an exception if you do it wrong).
That being said, you don't need to wrap every single UI operation into SwingUtilities.invokeLater() – if the code you're writing is already executed by the EDT this isn't needed. So the ActionListener for a button click doesn't need this. But a listener on an external object, running in some other thread, that updates a JLabel somewhere – there you need it.
Swing was not written to be a thread safe GUI toolkit so all GUI updates should happen from a single thread to avoid any deadlocks. In Swing this is the Event Dispatcher Thread (EDT).
See Concurrent in Swing from the Java tutorial for more details. It also references this blog entry on why it is hard to write a multithreaded GUI toolkit.
All the painting of the components should be performed in a single thread, so, they are rendered properly. That way the component will know, what part has already been painted and which part hasn't.
If you invoke a "painting" related method ( paint, update, paintComponent, show, setVisible, pack etc. ) outside the EDT, you'll be trying to paint in two different threads, and that may bring problems.
When you need to use another thread to update the UI, you should invoke it with the invokeLater facility, which in turn will put it in the EDT for you, so you still paint in the same thread.
You don't need to use it, if you're coding in a method that runs in the EDT already ( for instance, actionPerformed or paint or one of those ) Or if you are executing code not UI related ( for instance, processing files in the background etc. )
To better understand all these concepts read:The single thread rule
SwingUtilities.invokeLater()
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.
...
Repeating others: Swing is not thread safe so one thread must do all the updates to avoid concurrency problems. invokeLater is an utility method to execute something inside the event processing thread.
Why doesn't Swing does it internally: this is my impression... I think because it would be overkill -to check every place where an update is taking place. It would bloat the Swing code, dificult the review and maintainability of the code.
By the other hand it's not that dificult for an application to know if it's not executing inside the GUI thread and call invokeLater. It will be when the own application launched some thread before.

Categories