I'm developing a small app, which would have Swing GUI. App is doing IO task in another thread, when that thread finishes GUI should be updated acordingly to reflect thread's operation result. Class running in a (worker, non-GUI) has object passed to it in contructor which would be used for updating GUI, so I don't need to put GUI stuff in a non-GUI class, but rather pass object for updating GUI to that class.
As I understand form reading here, (thread/swing) safe options for updating (changing) Swing GUI would be to use javax.swing.SwingUtilities.invokeLater(), javax.swing.SwingUtilities.invokeLaterWait() and/or javax.swing.SwingWorker() which basically are doing the same thing.
This all threading issue with Swing is a little confusing for me, and yet I need to use threads to do anything meaningful in GUI apps and not hung GUI while processing in EDT, so what interests me for now is this:
Are invokeLater and invokeLaterWait like sending message to EDT and waiting for it do it when it finishes processing messages that were before that call?
is it correct from Swing thread safety aspect, to do something like this:
interface IUPDATEGUI {
public void update();
}
// in EDT/where I can access components directly
class UpdateJList implements IUPDATEGUI {
public void update() {
// update JList...
someJList.revalidate();
someJList.repain();
}
}
class FileOperations implements Runnable {
private IUPDATEGUI upObj;
List<File> result = new ArrayList<File>; // upObject is accessing this
public void FileOperations(IUPDATEGUI upObj) {
this.upObj = upObj;
}
private void someIOTask() {
// ...
// IO processing finished, result is in "result"
}
public void run() {
someIOTask();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
upObj.update(); // access result and update JList
}
}; );
}
}
In case this isn't correct then how should this be done?
If I could, I would prefer to use invokeLater instead of SwingWorker if possible, because I wouldn't need to change my whole class and it's somehow more neat/distinct me (like sending a message in Win32 apps).
Thanks in advance.
Using invokeLater() and invokeAndWait() passes the Runnable parameter into the queue awaiting execution in the EDT. So calling invokeLater() will cause the Runnable to execute in the EDT when the EDT is able to process the request. invokeAndWait() simply waits (in the calling thread) until this execution takes place.
Using SwingWorker is ideal if you want to do background tasks that notify the EDT either at the end of execution or in intermediate states. An example would be to pass the current progress of a process to a JProgressBar.
For your example it seems that SwingWorker is a better choice but if you don't want to change your code too much then calling invokeLater() when the process is done will be just fine.
I'd recommend not using the invokeAndWait until java 7. I found a spurious wake-up on this method that can cause really painful bugs. For me it led to some really rare and hard to debug null pointer exceptions.
http://bugs.sun.com/view_bug.do?bug_id=6852111
It's fixed as of java 7 b77.
invokeLater is fine. This puts the call into the AWT event queue, so that it will get executed in the EDT in due course. Your program will continue running, and does not wait for your callable to get called.
Related
I'm currently working with a thread control class someone else wrote. It is used for a java swing application. I have two methods, but I am confused as to why I am getting different behaviors from both. From what I know and read about the event dispatcher thread and Swing, there should be no difference in the two methods below. Apparently, this is not true.
//If this is the AWT Event Processing thread then run the code immediately,
//otherwise schedule it for later processing
public static void runWithEventThread(Runnable r)
{
if (EventQueue.isDispatchThread())
{
r.run();
}
else
{
EventQueue.invokeLater(r);
}
}
//Schedule the runnable for later processing by the AWT Event Queue
public static void runLaterWithEventThread(Runnable r)
{
EventQueue.invokeLater(r);
}
When using runWithEventThread() to display popups while updating GUI (new buttons/repainting), I found that the GUI would mess up sometimes. However when using runLaterWithEventThread(), it was all fine, no issues.
Only problem is that when using runLaterWithEventThread() I found that when I had multiple popups that would be displayed one after the other (after OK clicked) all popups were displayed at once.
From what I understand, both the methods should be doing the same thing. Can someone please explain what is going on
If your first method is executed from the event thread, it MAY act differently than the second method: If there are any events currently waiting on the event thread, those events will be processed BEFORE your run() method is executed if you use the second method, but if you use the first method, your run() method will be executed immediately, and any existing events on the queue will be run AFTER your run() method finishes.
I'm refactoring some code that runs a multi-stage process. Each step is inside a nested java.awt.EventQueue.invokeLAter.... call. It looks a little like this:
import java.awt.EventQueue;
public class NestedInvokeLater {
/**
* #param args
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
changeTabPanel();
copySomeFiles();
enableNextButton1();
upDateProgressBar(10);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
readInFiles();
doSomethingToFiles();
upDateProgressBar(15);
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
doSomethingElse();
upDateProgressBar(100);
}
});
}
});
}
});
};
}
I am new enough at Java that I don't get the point of nesting these calls to add 'jobs' to the EDT, and I'm not 100% confident with fiddling with these calls either. I think I understand what the invokeLater call does, and what each step does. Please correct me if this understanding is wrong:
invokeLater is used to add some invocation to the list of jobs to be done in the Event Dispatch thread. Java then deals with when/how each invocation is done, ensuring that the EDT and in turn the GUI doesn't lock as it performs jobs 'in the background'.
Nesting these calls says to me that we should queue a set of jobs, one of which is to queue something, which will queue some jobs....one of which is to queue something. But the first inner invocation is only ever queued once the previous job is done. Everything occurs sequentially (this is in line of my understanding of the whole process), but I don't see why you would use nested requests to queue jobs to do so. I would have, if I was writing this from scratch, have simply created functions for each invocation and called them in turn.
I recognise, being only a novice at Java I am probably missing something huge that makes this nesting important. But there is no documentation of this, and no commenting in the code about the nesting.
What am I missing? What, if anything is the point in this code?
There is no point in doing so many nested invocations. It is based on a good intention, but it's badly implemented.
If you want to do this properly, use a SwingWorker.
The documentation of SwingWorker has a neat example of how you should implement performing several tasks in the background of the application (the PrimeNumbersTask class showed there).
Edit: Here's an example of what you should do with SwingWorker in your case.
class SequentialInvoker extends SwingWorker<Void, Integer> {
#Override
public void doInBackground() {
changeTabPanel();
copySomeFiles();
enableNextButton1();
setProgress(10);
readInFiles();
doSomethingToFiles();
setProgress(15);
doSomethingElse();
setProgress(100);
}
}
To actually show the progress on a progress bar, take a look at the following code, copied from the SwingWorker documentation:
JTextArea textArea = new JTextArea();
JProgressBar progressBar = new JProgressBar(0, 100);
SequentialInvoker task = new SequentialInvoker();
task.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer)evt.getNewValue());
}
}
});
With this code, your progress bar will show the progress as the SwingWorker works.
One advantage of doing it this way is that other queued up things get to run in between. So, in between the section that does changeTabPanel() and the part that does readInFiles(), the GUI will get to respond to the user clicking on a button etc...
The actual implementation is a bit of a confusing mess and illustrates (IMHO) why anonymous functions were not such a good idea. Your inclination to make the three parts "real" functions and call them sequentially is a good one. But, to maintain the same logic, what you really need to do is make them three runnables and have each invokeLater the subsequent one.
And #Cyrille is correct that doing these major tasks on the EDT is poor practice.
There are three jobs that are used in invokeLater here. Each one does a costly thing, call updateProgressBar and then adds the next job to the EDT.
The thing is, if the code just continued to the next costly thing instead of calling invokeLater to do it, the EDT would not have the chance to repaint the progress bar to show the new value of it. This is probably why the work is broken in three invokelater calls.
Now, this is not what I would call a good code. This is pretty bad practice: one should not do a long process in the EDT because it blocks everything and makes the GUI unresponsive. This should be changed so that the process is done in a separate thread, and then only call invokeLater to update the progress bar.
Edit: To answer more generally the question in the title: there is almost never a sensible reason to nest calls to invokeLater. When you are doing this, you say "queue this job so that it is done in the same thread but later when you feel it would be good". So it gives a chance to the rest of the GUI to repaint itself, like here. But it only makes sense if you have a long running process in the EDT, which you should always avoid.
The code you posted makes absolutely no sense to me - you can just write everything sequentially because you have no parallel threads running which might post events on the EDT. You need the first invokeLater() though, as you use Swing components.
But as your code suggests you are doing some relatively lengthy operations: reading files, do something with them, ... You should run these methods in a new worker thread, NOT the EDT. And, in the run() method of these worker threads, you'll need a call to EventQueue.invokeLater() to have your GUI updated.
After years of Java programming I always used to create my main() methods like this :
public static void main(String[] args)
{
runProgram();
}
But recently I studied some codes from the Web and saw this sometimes instead of the usual main() use above :
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
runProgram();
}
});
}
I simply want to know :
Why to use this instead of the usual main() way ? I can't see any difference when I give it a try.
What is the difference between these two ways ?
Thanks for reading me and your answers.
The docs explain why. From Initial Threads
Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.
and from The Event Dispatch Thread
Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.
Because the thread "main" started by VM is not the event dispatch thread.
A few Swing components from the API are not thread safe,which means that they may cause some problems like deadlock,So its better to create and update such swing components by using Event dispatcher thread provided by Swing but not from the main thread or any other thread created from main.
While the answers above are all correct, I believe they lack a correct explanation.
Yes, everything that interacts with Swing (creating the UI, updating it, adding new components or layouts, etc.) should be always done on the AWT event-dispatch thread (see this post for more information on the topic).
SwingUtilities.invokeLater() places your code in the FIFO Queue of the event-dispatch thread (EDT), so it will be executed from the EDT whenever it has finished the other tasks it was doing.
Having that said, the EDT should be used exclusively to run Swing-related tasks that are quick to perform (if you block the EDT, you block the whole UI).
There is no point using SwingUtilities.invokeLater() on the main method if you aren't using Swing/AWT (e.g. a JavaFX app or a terminal app).
If you want to perform some tasks that have nothing to do with Swing at all but they're required to start Swing (e.g. starting the Model and Controller in a MVC-like app), you could do it either from the EDT or the Main thread (see this post for a discussion on this topic).
There is actually more than 1 question.
Given Model View and Controller. (Mine are coupled a lot - View knows its Controller, and Controller knows View.)
Does new threads in Controller can be fired in basic manner - with the new Runnable(){ (...) run(){}} or it is required to do in some "swing way", to make it properly? Maybe with Timer or invokeLater()?
Second thing is - assuming that new thread has started - when it operates directly on view, setting some JTextFields (and so on) - do methods such as setThatTextFieldWithNewValue(msg) need to be synchronized as a result of being called from need thread? If so - is there any better approach that gives less coupling and less spend time thinking about needed synchronization?
there are a few ways how is possible to create, manage and notify MVC, for better help sooner post an SSCCE
Runnable#Thread is very confortable, stable and clear way, but I'd suggest to wrap all output to the Swing GUI into invokeLater, including thread safe methods as setText, append e.g. are ..
as Kumar Vivek Mitra (+1) metioned there is SwingWorker, but required deepest knowledge about Java essential classes, some trouble are there with exceptions recycle how to get exception from SwingWorker
about MVC maybe will help you my similair question
Swing is not Thread-Safe
1. The UI thread is the Event Dispatcher Thread, which is responsible for the Gui work.
2. Try working with Non-Ui threads outside the UI thread.
3. Yes offcourse you can fire a thread from within the UI thread, but its advisable to keep it out of
the UI thread, else the GUI may seems non-responsive.
(ie. the Non-UI work on the Non-UI thread OUT of the UI thread which is responsible for the UI Work)
4. Well there is a swing way too... use SwingWorker, this handles the synchronization between UI and Non-UI thread.
Edited part:
// PLEASE NOTE ITS NOT GOOD TO ADD COMPONENTS DIRECTLY ON THE FRAME/JFRAME, BUT I AM DOING THIS JUST TO SHOW, WHAT I MEANT.
public class MyClass extends JFrame{
private final JButton b;
public MyClass(){
this.setSize(300,300);
this.setComponent();
this.setHandler();
}
public void setComponent(){
b = new JButton("Click");
this.add(b);
}
public void setHandler(){
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Do whatever you want...
}
});
}
public static void main (String[] args) {
EventQueue.invokeLater(new Runnable(){ // UI THREAD
public void run(){
MyClass s = new MyClass();
s.setVisible(true);
}
});
}
}
Main method is short lived in Swing, The main method() schedules the Construction of GUI to the Event Dispatcher Thread (EDT), and then quits. So its EDT responsibility to handle the GUI. So its always advisable to keep the Non-UI work on the Non-UI thread away from EDT.
Anything in swing has to run on the EventQueue. If you have a method called from swing it will already be running there (as in an Action listener). If you don't know if you're on the event queue, EventQueue.isDispatchThread() will tell you. When you know you're not, reference a swing class or method using EventQueue.invokeLater() or invokeAndWait if you need to see results. (This must be done from the main method.)
Be very careful about this; you have to check your code. If not, my experience is that the swing UI will be just a little bit flakey, with the occasional unreproducable oddity. There's no easy way around eyeballing each line of code.
Actually, there is. Do everything on the EventQueue, then you won't have to worry. You're probably not doing a whole lot of work outside swing anyway. If you are, it's probably worth the loss of speed to avoid multithreading problems. If your non-swing work is extensive but simple, use the SwingWorker class. It gives you an extra thread under highly controlled conditions and should save you a lot of grief.
Your classes (View and Controller) are independent of threads, and should work just fine all running in one thread. Don't confuse classes and threads. (I'll admit, I'd be tempted to have the Controller firing off threads in all directions, but you have to be prepared to be very careful and know everything there is to know about multithreading.)
If you do multithread, the EventQueue can be a bit handy because you don't have to protect fields referenced only there--it's an island of single threading in a dangerous sea. On the other hand, don't do any synchronization there; you'll block your UI. You can launch threads from there and you may have to just to avoid blocking. (Once you start multithreading, it's hard to stop.)
The easiest way would be:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// Run your code here.
}
});
For more complex tasks (send process chunks to ui thread, respond to jobFinished):
new SwingWorker<String, String>() {
#Override
protected void done() {
}
#Override
protected void process(List<String> arg0) {
}
#Override
protected String doInBackground() throws Exception {
}
}.execute();
I have a method called inside a button that run almost an infinite loop. I can't access the other buttons while running this method.
How I make to free the interface to access other buttons while running this method?
//methods inside the button
this.setCrawlingParameters();
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method
you need to use a SwingWorker
The way Swing works is that it has one main thread, the Event Dispatch Thread(EDT) that manages the UI. In the Swing documentation, you will see that it is recommended to never to long-running tasks in the EDT, because, since it manages the UI, if you do something computationally heavy your UI will freeze up. This is exactly what you are doing.
So you need to have your button invoke a SwingWorker so the hard stuff is done in another thread. Be careful not to modify UI elements from the SwingWorker; all UI code needs to be executed in the EDT.
If you click the link for SwingWorker, you will see this:
Time-consuming tasks should not be run
on the Event Dispatch Thread.
Otherwise the application becomes
unresponsive. Swing components should
be accessed on the Event Dispatch
Thread only
as well as links to examples on how to use a SwingWorker.
Start a new Thread:
// In your button:
Runnable runner = new Runnable()
{
public void run()
{
setCrawlingParameters(); // I removed the "this", you can replace with a qualified this
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method
}
}
new Thread(runner, "A name for your thread").start();