As far as I know, there are 3 threads in a Swing GUI application:
the main application thread, which executes the main() method
the toolkit thread, which receives the system events
the event dispatching thread, dedicated to the painting and event handling of the GUI stuff
Generally, the main method just makes a call to SwingUtilities#invokeLater(Runnable) in order to initialize a window and so on, thus the GUI initialization is made on the EDT... BTW, as far as I know (again), everything that touches the GUI must be executed on the EDT...
Questions: What is the main thread used / usable for? Does it just die after the call to invokeLater()? Does it consume resources? Can I (and is it a good practice to) use it to perform... I don't know... Network stuff?
A Swing programmer deals, actually, with 3 kinds of threads:
Initial threads (the one that executes the initial application code,
our main here)
The EDT (as you metioned)
Worker threads (to deal with background tasks)
The inital thread creates the Runnable to run swings tasks and schedule it in the EDT. After that, the program is primarly driven by the GUI, and the application code survives and can continue to execute other tasks (Network staff as you noticed) and consumes resources as much as it needs.
Any Swing component method must be invoqued by the EDT (but some of them) because they swing method are not "thread-safe". So,
SwingUtilities#invokeLater(Runnable)
just queues the runnable in the EDT task list and wait for its turn to run.
The doc here is quite helpful.
The main thread in a Java program dies when control reaches the end of main().
In the program architecture that you describe, the main thread already has created the EDT and maybe other threads by that point, and those other threads keep the JVM alive.
Every thread in Java is either a daemon thread, or a non-daemon thread. The latter is the default case for a new Thread. You have to call t.setDaemon(true) if you want a daemon.
A JVM will keep running as long as there is at least one non-daemon thread still alive.
What is the main thread used / usable for?
It is usable for any purpose that you would use any other thread for. It executes whatever code you write for it to execute.
Related
I was comparing the differences between Swing's SwingWorker and Android's AsyncTask classes. While Android has a Main Thread/UI Thread and then spawns a background thread (using AsyncTask), SwingWorker has three threads that are involved -
Current thread
Worker thread
Event Dispatch Thread.
And then I also came across the statement (in docs) -
Often, the Current thread is the Event Dispatch Thread.
Now, what does this mean?
Does it mean that Swing also has only 1 thread - the Main Thread and
even the events are received on the same thread OR
Is it different for different JVM implementations?
This is only valid for Swing, which shares some similarities with Android UI programming but is indeed not the same.
A little bit of context
The EDT (Event Dispatch Thread) is Swing's thread dedicated to handling UI events (mouse and keyboard input, events on controls, rendering of the UI, etc...).
This is an Event Loop model, similar to what is done in Android.
The fact that event listeners in Swing are executed on the EDT is the root cause for freezing UIs in Swing applications: developers misunderstanding the threading model often put long-running code in the listeners, which blocks the EDT and thus the GUI.
SwingWorker was introduced to better guide developers in separating UI updates from long-running background code. It spawns a dedicated background thread for the I/O processing (or long-running task) in doInBackground and executes UI updates in done and process methods. While these 3 methods guarantee in which thread they'll be executed, all other methods are executed in the current thread.
What is meant by the sentence you quoted
The whole reason for SwingWorker to exist is to properly initiate a long-running process from the GUI, without blocking the GUI.
Often, it will be in reaction to a user's input (e.g. clicking a Button). Since reactions to the user's input (implemented as Listeners) are always executed in the EDT by the Swing framework, unless you happen to call execute or get from another thread explicitly, it will get executed on the EDT.
By the way, execute is "fire-and-forget" and is the typical use-case (call it from a listener). get on the other hand blocks, and is not suited to be called from a listener (it would defeat SwingWorker's purpose, call it on your own threads if needed)!
In my application I have a main frame window GUI, that launches a task in an executor service.
The submitted task generates output and stores in a file on Disk.
As soon as the o/p is generated GUI (observer) is informed of the o/p generated.
Here the problem is I am keeping a wait loop inside the main frame and as soon as a notification is received, the main panel is repainted on the main frame.
For small tasks this works fine, but as the size of the threaded task increases. The wait loop time increases and the GUI main window turns black till computations are done.
Can you please help me in correcting the design. Also How can a SwingWorker thread help in this case.
The wait loop time increases and the GUI main window turns black till computations are done.
Then you long running task is executing on the Event Dispatch Thread (EDT) which prevents the GUI from repainting itself. You need to execute the long running task in a separate Thread. A SwingWorker is a separate Thread which has an API that also allows you to execute code on the EDT as required, for example when the code finishes executing or when you have intermediate results.
Read the section from the Swing tutorial on Concurrency for more information. You can always search the forums for example of using a SwingWorker.
1)
Wait loops are the bane of all that is GUI. They are OK in other threads you have spawned, tricky in Executors (as they sometimes have limits on number of Threads, depending on which you use), and are completely out of the question on the EDT. That is the reason for your "blackscreen"
2)
Instead of using a custom (I assume it's custom) signal protocol and a wait loop, you could use one of the utility classes in Swing. For example, SwingUtilities has a couple of nice methods - invokeLater and invokeAndWait that take a Runnable and execute it on the EDT as soon as they can. Using this instead of the signal you have will allow you to not block the EDT and make your GUI responsive.
3)
If you really want to use a SwingWorkeryou may want to look through the documentation for it. It is essentially a way to do background tasks and report progress or completion/result to the EDT. Currently it uses an ExecutorService with 2 background threads, so having a lot of long running tasks on them is not a good idea (they will block each other). When creating a SwingWorker you would specify the method to be ran in the background, the method to be ran on the EDT when intermediate results are available, and the method to be ran on the EDT when you're finished either successfully or in error.
4)
This does not pertain to the question at hand, but if you ever get into a situation where you need a wait loop in the EDT and cannot avoid it using another design or technique, you can always switch to using a Timer. It can be setup to be called every x milliseconds without blocking the EDT and turned off once you are satisfied with some condition.
I know what "thread" means and if I understand the event dispatching thread (EDT) as
"just a thread", it explains a lot but, apparently, it does not explain everything.
I do not understand what is special about this thread. For example I do not understand why we should start a GUI in a the EDT? Why the "main" thread is bed for GUI? Well, if we just do not want to occupy the main thread why we cannot start GUI just in "another thread" why it should be some "special" thread called EDT?
Then I do not understand why we cannot start the EDT like any other thread? Why we should use some special tool (called invokeLater). And why GUI, unlike any other thread, does not start immediately. We should wait until it is ready to accept our job. Is it because EDT can, potentially execute several task simultaneously?
If you decide to answer this question, could you pleas use a really simple terminology because otherwise, I am afraid, I will not be able to understand the answer.
ADDED:
I always thought that we have one "task" per thread. So, in every thread we execute a predefined sequence of commands. But it seems to me that in the event dispatching thread we can have sever task. Well, they are not executed simultaneously (thread switches between different task but there are still several task in one thread). Is it right? For example there is one thread in the EDT which display the main window, and then additionally to that we sent to the EDT another task which should update one of the window components and EDT will execute this new task whenever it is ready. Is EDT differ from other threads in this way?
The event dispatching thread is the thread that handles all GUI events and manages your Swing GUI. It is started somewhere in the Swing code if you have any GUI in your program. The reason it is done behind the scenes is because of simplicity - you do not have to bother with starting and managing an extra thread by yourself.
Regarding the fact that you have to update your GUI with invokeLater() it is because of concurrency issues. The GUI can be modified only from one thread because Swing is not thread safe(it is worth to note that most of toolkits are not thread safe, there is a nice article that gives some ideas why). This is why you have to submit all GUI updates to run on EDT.
You can read more on concurrency in Swing and event dispatching thread in Sun tutorial on concurrency in Swing. Also, if you would like to see how this could be done in a different way you might like to check out SWT toolkit. In SWT you have to manage EDT by yourself.
I always thought that we have one
"task" per thread. So, in every thread
we execute a predefined sequence of
commands. But it seems to me that in
the event dispatching thread we can
have sever task. Well, they are not
executed simultaneously (thread
switches between different task but
there are still several task in one
thread). Is it right? For example
there is one thread in the EDT which
display the main window, and then
additionally to that we sent to the
EDT another task which should update
one of the window components and EDT
will execute this new task whenever it
is ready. Is EDT differ from other
threads in this way?
No, the EDT is not fundamentally different from other threads. And "task" is not a good word to use, because it could be confused with OS-level processes (which are also often called task). Better use Runnable, the interface used to give code to the EDT to execute via invokeLater().
The EDT is basically connected to a queue of things it has to do. When the user clicks a button on the GUI, a Runnable that notifies all listeners attached to the button goes into the queue. When a window is resized, a Runnable doing revalidate&repaint goes into the queue. And when you use invokeLater(), your Runnable goes into the queue.
The EDT simply runs an endless loop that says "take a Runnable from the queue (and if it's empty sleep until you're notified that it's not) and execute it.
Thus, it executes all those little Runnable pieces of code one after another, so that each of them basically has the GUI all to itself while it runs, and doesn't have to worry about synchronizing anything. When you manipulate the GUI from another thread, this assumption is broken, and you can end up with the GUI in a corrupted state.
What is the EDT?
It's a hacky workaround around the great many concurrency issues that the Swing API has ;)
Seriously, a lot of Swing components are not "thread safe" (some famous programmers went as far as calling Swing "thread hostile"). By having a unique thread where all updates are made to this thread-hostile components you're dodging a lot of potential concurrency issues. In addition to that, you're also guaranteed that it shall run the Runnable that you pass through it using invokeLater in a sequential order.
Note that it's not just that you're dodging the concurrency issue: you must respect Sun's guidelines regarding what must and what must not be done on the EDT or you'll have serious problems in your application.
Another benefit is that some Swing components tend to throw unwanted exceptions and when this happen they're automagically dealt with and won't crash the EDT (AFAIK if you really manage to kill the EDT it is automagically restarted).
In other words: you don't have to deal with all the broken Swing components and the exceptions they throw yourself: the EDT is taking care of that (just take a look at the countless Swing bugs throwing exceptions in Sun's bug parade, it's fascinating... And yet most apps keep working normally).
Also, by doing only what's mandatory in the EDT allows the GUI of your app to stay "responsive" even tough there may be tasks running in the background.
The important thing to remember is that Swing classes are not thread-safe. This means that you always should call Swing methods from the same thread, or you risk getting weird or undefined behavior.
So the solution: only call Swing methods from a single thread. This is the EDT thread - it's not special in any way other than that it is the thread designated to call swing methods from.
Now you may ask why are Swing methods not thread safe? After several unsuccessful attempts, GUI toolkit designers discovered that it's inherently impossible to design a thread-safe GUI toolkit. Too often events are passed in opposite directions (input events from bottom to top, application events from top to bottom) which always leads to deadlocks. So that's just the way it is.
Can anyone help me with the difference between pauseAWT() and awtSleep()? Also when to use one over other?
junit.extensions.jfcunit.JFCTestCase in the AWT testing stuff of JUnit? I think the Javadocs are pretty clear:
pauseAWT: Pause the awt event queue until it is released by releaseAWT() or the end of the test is reached.
awtSleep: w/o argument: Suspends the test for up to a maximum period of time, and allows the AWT Thread to resume temporarily / w/ argument: Suspends the test for up to the specified (maximum) period of time, and allows the AWT Thread to resume temporarily.
So, the first pauses the AWT thread, the second pauses the test and allows the AWT thread to resume. Bear in mind that AWT operates in a separate thread, commonly called the EDT (Event Dispatch Thread). It looks like you would use these two methods in tandem to ensure a replicable state for testing.
I have a java app in which I use a thread. My thread runs every 20 seconds but, when it runs it kind of blocks the UI ... i. e. whenever the thread is running and the user clicks on button on anything on UI it doesnt respond sometimes.
Could anyone tell me a solution to this problem.
in java Swing, any change made to the state of the UI should be done in a single pre-existing thread called the EDT (event-dispatcher thread).
if that's not the case, you typically experience weird glitches / freezes. one of the most common symptom is that part of the UI becomes gray (except since java 1.6, where the ui is still painted like before, but unresponsive).
the good way to go is to use a dedicated method to queue your changes to the UI in the EDT :
SwingUtilities.invokeLater(Runnable toRunInEDT);
note that if you call invokeLater, the runnable is executed after all currently queued event have been dispatched. that means that the next line of code could be executed before the code in the runnable. there is a synchronous version as well (which should not be executed from the EDT):
SwingUtilities.invokeAndWait(Runnable toRunInEDT);
Some additional tips, on top of what edralzar said:
You can use the convenience method SwingUtilities.isEventDispatchThread() to check if code is in fact running on the event dispatch thread. And, like edralzar said, any code that creates GUI components, modifies the state of GUI components or reads the state of GUI components should run on the Event Dispatch Thread.
Another thing to consider, however, is that code running on the EDT should be able to execute rather quickly. So you cannot just solve things by running everything on the event dispatch thread. If you do the following, your GUI will be frozen for five seconds:
SwingUtilities.invokeLater(new Runnable(){
public void run(){
try{
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){
//Ignored in this example
}
}
});
Why is it frozen? Because all GUI events and GUI updates are performed on the EDT, and if the EDT sleeps for 5000 miliseconds, no GUI updates can be performed during that time.
This article might be an interesting read.
Sounds to me like the thread you're referring to (that runs every 20 seconds) is also the thread that governs the UI.
The solution is to separate the two processes onto different threads.