Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top