Search code examples
javaweb-servicesservletsjava-threads

Start new thread within a Servlet


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?


Solution

  • 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();