Feras Odeh
Feras Odeh

Reputation: 9306

execute SwingWorker multiple times

I want to be able to use SwingWorker subclass multiple times. Is this possible?

I have read in the java doc:

SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.

Upvotes: 10

Views: 7682

Answers (4)

Adir Dayan
Adir Dayan

Reputation: 1627

You can just call again your swing worker from done() method (depend how your code desinged)

MySwingWorker worker = new MySwingWorker();
worker.setData(this.getData());
worker.execute();

Regard setData() and getData()

It's just simple hashmap i'm using to pass the inputs data to my swing worker, so for rerun it, i just passed the same inputs to the new instance of swing worker

Upvotes: 0

kar
kar

Reputation: 11

Try doing this:

  private void startTask() {// main method that creates the background task or class that implements the SwingWorker

    AppContext  appContext = AppContext.getAppContext();
    if(appContext!=null){
        appContext.remove(SwingWorker.class); 
    } 
    MassiveMigrationTask task = new MassiveMigrationTask();// class that implements the SwingWorker
    task.execute();// this process implicitly adds the SwingWorker.class to the appContext
    }

As the description: "The AppContext is a table referenced by ThreadGroup which stores application service instances."

So this issue is happening basically because the AppContext is saving the name of the thread called SwingWorker..., so if you try creating another instance of the thread you'll probably have no success, because it evaluates that thread name before executing a new one or at least put the new in the heap of threads to be executed, feel free consulting the code here:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/awt/AppContext.java

PS: Important :"If you are not writing an application service, or don't know what one is, please do not use this class"

Upvotes: 0

user2772139
user2772139

Reputation: 11

You cannot instantiate as many instances you need and execute them. In SwingWorker class exists javax.swing.SwingWorker.MAX_WORKER_THREADS = 10. So you can execute a maximum 10 instances. An instance is freed only it spend 10 minutes in idle time. Do not use SwingWorker instance as a Thread instance;it is not a thread.

Upvotes: 1

Boris Pavlović
Boris Pavlović

Reputation: 64640

One instance of a class implementing SwingWorker can be indeed ran only once. There are no limitations on instantiating as many instances as you need and running them.

Upvotes: 10

Related Questions