user3876178
user3876178

Reputation: 241

Simultaneously processing in one Servlet

I have a Servlet which recieves a request, has to process 5 tasks (Grab data Form external Servers) and send all the data back to the client ordered.

How to process the 5 Task simultaneously and continue with the servlet code after all 5 tasks are completed?

Upvotes: 2

Views: 191

Answers (3)

Eric
Eric

Reputation: 24910

5 seconds is too long, it might take up the web server resource, you can let the client to send a request A, which trigger your 5 seconds task, but it don't wait, return immediately.Since you know it will take 5 seconds, you can send another request B, 5 seconds later, to get the data. If data not ready yet, you can request after another 5 seconds, until MAX_RETRY_COUNT (defined by yourself) reached.

Upvotes: 0

Sid
Sid

Reputation: 1144

Another option is the ExecutorService. There are a variety of examples available including the following:

Here is some example code taken from the first link found above:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}

Upvotes: 1

Braj
Braj

Reputation: 46841

You can use CoundDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

sample code:

    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(5); // 5 tasks

    class Worker implements Runnable {
        private final CountDownLatch startSignal;
        private final CountDownLatch doneSignal;
        private final int threadNumber;

        // you can pass additional arguments as well
        Worker(CountDownLatch startSignal, CountDownLatch doneSignal,
                                                   int threadNumber) {
            this.startSignal = startSignal;
            this.doneSignal = doneSignal;
            this.threadNumber = threadNumber;
        }

        public void run() {
            try {
                startSignal.await();
                doWork(); // actual work to be performed here    
                doneSignal.countDown();
            } catch (InterruptedException ex) {
                LOGGER.error(ex);
            }
        }
    }

    // 5 new threads are started
    for(int i=1;i<=5;i++){
        new Thread(new Worker(startSignal, doneSignal, i)).start();
    }

    startSignal.countDown(); // let all threads proceed
    try {
        doneSignal.await(); // wait for all to finish
        // all 5 tasks are finished and do whatever you want to do next
    } catch (InterruptedException interruptedException) {
        LOGGER.error(interruptedException);
    }

Read more... and Find more examples...

Upvotes: 1

Related Questions