Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between SwingWorker and Executor

I am using SwingWorker to execute some heavy load tasks on an application I am making . Although today I got across the Executor class and this example :

Executors.newCachedThreadPool().execute(new Runnable() {
                    public void run() {
                        someTask();     
  });

Can someone explain the reasons why one would use SwingWorker instead of the above example ? This is the way I am currently using SwingWorker :

SwingWorker worker = new SwingWorker() {            
protected Object doInBackground() {
    someTask();
return null;
}
};
worker.execute();
like image 877
Giannis Avatar asked Jan 08 '12 18:01

Giannis


2 Answers

1) SwingWorker is created as bridge betweens Java Essentials Classes and Swing by implements Future, and quite guarantee that outoput from methods process, publish and done will be on EventDispatchThread

2) you can invoke SwingWorker from Executor, this is most safiest methods how to create multithreading in Swing by implements SwingWorker

3) notice carefully with number or thread, because Executor doesn't care somehow about SwingWorkers life_cycle

4) another important notice and here

5) for listening states from SwingWorker you have to implements PropertyChangeListener

like image 165
mKorbel Avatar answered Oct 17 '22 19:10

mKorbel


The SwingWorker has additional methods process() and done() which are automatically executed in the event dispatch thread. This comes in handy if you plan to display your progress or final results in a user interface.

like image 41
Howard Avatar answered Oct 17 '22 21:10

Howard