Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Have a question with using multiple SwingWorker threads  RSS feed

 
Karthika Nagarajan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a Swing UI in which on click of Search button, I trigger the Search in 6 different modules in 6 Swing Worker threads. The results are returned by each Swing Worker class to the calling class.

I tried to use the below code to get the values returned from each thread. Now, I want to continue further only after all threads finish their execution. How to achieve this?

thread1.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (StateValue.DONE == thread1.getState()) {
try {
result1 = thread1.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

}
});


I got several examples where the UI is updated direstly from multiple threads. I want the values to be returned to calling class because of below reasons:

1) When even one worker thread fails for some reason, I dont want to show the any result in the UI
2) Earlier, I was updating the UI in done() of every worker class. But, UI became inconsistent. E.g When one thread is in progress, other threads were completed and updating the UI which I dont want to do.

Thanks!!!
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The "ranch office" forum is for discussions regarding the coderanch forums itself. So, let's move this topic to the Swing forum.

Henry
 
Piet Souris
Rancher
Posts: 1979
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Karthika,

the 'done()' method is ideal. What kind of inconsistencies do you get?

If you don't want to have your 'done()' method update your GUI, then
let it store the result to some result container. It can also update a
list of completed swingworkers, so that you can see if all tasks are
finished. And only then could you update your GUI.

If you are afraid that some task may crash, then one way to
detect it is to have a Timer check on a regular base if the tasks
are alive, and if not, check it with the list of completed tasks.

Since all the above code is executed on the EDT, you should not have
any synchronization problems.

Greetz,
Piet
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!