I have the following method:
public Object someMethod(Object param) {
return performLongCalculations();
}
Some time consuming calculations I placed in a separate method:
private Object performLongCalculations() {
...
}
The problem is that it returns some calculation result. These calculations are performed in the EDT and lead to freezing the UI.
I tried to solve it with the following way:
public Object someMethod(final Object param) {
Object resultObject = new Object();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Object> future = executorService.submit(new Callable<Object>() {
@Override
public Object call() {
return performLongCalculations(param);
}
});
executorService.shutdown();
try {
resultObject = future.get();
} catch (InterruptedException | ExecutionException e) {
// ...
}
return resultObject;
}
But the thread is blocked on the call to future.get(); until the calculations are completed. And I think it also runs in EDT.
Next I tried to use SwingWorker:
public Object someMethod(final Object param) {
SwingWorker<Object, Void> worker = new SwingWorker<Object, Void>() {
@Override
protected Object doInBackground() {
return performLongCalculations(param);
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException e) {
}
catch (ExecutionException e) {
}
}
};
worker.execute();
// what should I return here?
}
Here I need to return the result, but it returns before the end of the thread that runs in parallel with EDT.