Affi
Affi

Reputation: 152

Using multiple threads inside java swingworker background thread

I am running jobs as background process using java swingworker

protected static class BackgroundTask extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() {
    //while (!isCancelled()) {
    Build_JobParams.runJob();
    //}
    return null;
}

Now, I need to call multiple times (asynchronously) the background process using different parameters. As it is background process, 2nd call is overriding the first call parameters. One way I tried is using multiple threads like Thread t1 = new Thread(){ ... but it is throwing exceptions intermittently.

Any better suggestions. Note, I can't wait in the done() { .. method to invoke the 2nd call as I have making many calls and not sure of the number of calls initially. Please suggest if there is some good way.

Upvotes: 1

Views: 500

Answers (1)

akki
akki

Reputation: 451

You can use ExecutorService with a fixed size thread pool. You can find more information on how to set the correct pool size here

Here is what can try:

  1. Create an executor service:

ExecutorService service = Executors.newFixedThreadPool(5) // setting arbitrary value to 5

  1. Create a callable by implementing Callable interface

  2. Call Build_JobParams.runJob() in call method.

  3. service.submit(/** submit instance of "Callable" here **/)

If Build_JobParams.runJob() is not returning any value you can also call service.execute but in that case you need to create a Runnable.

Hope this helps!!

Upvotes: 2

Related Questions