0

I have a servlet, which calls a web service.

The servlet does NOT need to wait for the servlet to conclude since it does not require any information from its response.

Can I generate a new thread to call the web service?

Would it be done with new Thread(callWSMethod()).start()?

If this is not recommended, what is a better way?

JLLMNCHR
  • 1,309
  • 3
  • 22
  • 43

2 Answers2

0

Since you don't need any JEE resources like UserTransaction, I feel that it is fine to do so. However, please do read till the end.

In earlier versions of JEE, I remember that this wasn't recommended since the starting a thread won't have the managed resources and contexts like EJBs, Connection Pool, JTA transactions, etc. However, I am not sure if it is still not recommended in JEE7. There still is ManagedExecutorService in JEE7 which can be used for this purpose.

However, I have done it many times without any problem with ExecutorService directly, as long as I didn't want any managed resource like the ones mentioned earlier. I have used ExecutorService always and not Thread directly. The only "watch-out-for" is that one must shutdown the ExecutorService in some manner at the end of the processing.

But many disagree with this approach. Let's hear from the others too.

Sree Kumar
  • 766
  • 3
  • 6
0

it looks like the servlet is only interested to trigger (fire-and-forget) a process/thread distributed somewhere else. In this case I would not worry about Transactions or Managed Resources as you are invoking an isolated service which does not share anything with your app.

You can just simply start a thread:

public class MyThread extends Thread {

public void run(){
   // callWSMethod
}

}

An elegant way is to use Java Lambda

Runnable callWSMethod =
    () -> { // perform call};

Thread thread = new Thread(callWSMethod);
thread.start();

Thread Pool

The servlet might receive multiple requests, if you expect a large volume you want to limit the number of threads created by your applications. You can do that using ExecutorService

ExecutorService executorService = Executors.newFixedThreadPool(5);

executorService.execute(new Runnable() {
  public void run() {
    // perform call};
  }
});

Dont forget the shutdown

executorService.shutdown();
Beppe C
  • 4,511
  • 1
  • 5
  • 23