Consider following code:
SwingWorker<Void, Void> sworker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
try {
for (int j = 0; j < 5; j++) {
Callable<Object> worker = new MyCallableImpl();
Future<Object> future = executor.submit(worker);
array[j] = future.get();
}
} catch (InterruptedException e) {
// some code here
} catch (ExecutionException e) {
// some code here
}
// some code here
executor.shutdown();
return null;
}
};
sworker.execute();
As I said in the title: is this a good practice to invoke ExecutorService inside doInBackground() method of SwingWorker? It works for me (JDK1.7), GUI is not blocked and multiple threads from Executor pool are running in background, but still I have some doubts...
Below are some benefits: Executor service manage thread in asynchronous way. Use Future callable to get the return result after thread completion. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically.
ExecutorService in Java Example It also provides a submit() method which can accept both runnable and callable objects. In the following example, we will create an ExecutorService with a single thread and then submit the task to be executed inside the thread.
Here is a code example: ExecutorService executorService = Executors. newSingleThreadExecutor(); Set<Callable<String>> callables = new HashSet<Callable<String>>(); callables. add(new Callable<String>() { public String call() throws Exception { return "Task 1"; } }); callables.
ExecutorService is actually a `BlockingQueue` with Threads attached to it. Threads that are attached to the BlockingQueue will be taking tasks from the queue and execute them. Basically, the threads are the consumers of the queue. And you will be submitting tasks to the queue for the consumers to consume.
The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.
We can assign tasks to the ExecutorService using several methods including execute(), which is inherited from the Executor interface, and also submit(), invokeAny() and invokeAll().
The above code doesn't make much sense to me.
If the objective here is to ensure that the GUI remains responsive while a long-running task is being executed, then there's no need to use the ExecutorService
since the SwingWorker
already provides that mechanism.
can executing SwingWorkers instance from Executor
have to accepting that Executor doesn't care about SwingWorkers lifecycle and vice versa
have to implement PropertyChangeListener for SwingWorker
exmple here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With