I have a button that calls a method from the backing Bean. This method allows to extract data from parsing html code. While the method is running i have a dialog showing a progr
ExecutorService documentation
Instead of directly calling the method, convert the method into an ExecutorService
's task.
public class SearchEmailsTask implements Runnable {
private EmailSearcher emailSearcher;
public SearchEmailsTask(EmailSearcher emailSearcher) {
this.emailSearcher = emailSearcher;
}
@Override
public void run() {
emailSearcher.searchEmails();
}
}
You can use Callable
if you want to return something.
When you want call the method, submit that task to an ExecutorService
.
ExecutorService executorService = Executors.newFixedThreadPool(4);
SearchEmailsTask searchEmailsTask = new SearchEmailsTask(new EmailSearcher());
Future> future = executorService.submit(searchEmailsTask);
Keep a reference to the task.
private static Map > results = new HashMap >();
A map should be a good idea to store multiple Future
objects. You can of course go for something better if you want.
Call cancel on the task whenever required.
future.cancel(true);
Note:
Task should have suitable checks for thread interruption for proper cancellation.
To achieve this, refer to
Good luck.