Reputation: 2920
I have a @Stateless
bean where a method needs to return a status quickly but perform a long running task in a background thread. My approach has been to do the following:
Create a thread pool for executing these tasks, and make the threadpool a member variable:
final ExecutorService m_threadPool = Executors.newFixedThreadPool(5 /* Get from config*/, new ThreadFactory()
{
public Thread newThread(final Runnable r) {
return new Thread(r, "NotificationInputHandler Thread");
}
});
Split my service method into two parts: 1) createStatus and 2) performBigTask
public Result process(final List<String> input) {
final Result status = createStatus(input)
m_threadPool.submit(new Runnable() {
public void run() {
performBigTask(input);
}
});
return status;
}
My questions are: 1. Could this be done in a better way? 2. I am running on JBoss 7. Is there an app-server provided thread pool I could inject instead of instantiating my own?
Upvotes: 0
Views: 1411
Reputation: 2565
you can use @Asynchronous , have an other stateless session B bean to do your big task and annotate its method with @Asynchronous and then have you original session Bean lets call it A call before it returns the status
B:
@Asynchronous
public Future<SomeResult> performBigTask(List<String> input){
/*run your big task*/
return new Asynchronous<SomeResult>(bigTaskResult);}
A:
@EJB B b;
public Result process(final List<String> input) {
final Result status = createStatus(input)
Future<SomeResult>result= b.performBigTask(input);
//check if every thing went well or what ever logic you have
return status;
}
if you want to see how to manipulate Future here is a link oracle tutorial
Upvotes: 2