Why Multithreading is not working perfectly in AWS Lambda function?

Viewed 8378
public class LambdaFunctionHandler implements RequestHandler<Object, String> {

    @Override
    public String handleRequest(Object input, Context context) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello");
            }
        }
    Thread thread1 = new Thread(runnable);
    thread1.start();
    Thread thread2 = new Thread(runnable);
    thread2.start();
    Thread thread3 = new Thread(runnable);
    thread3.start();
    Thread thread4 = new Thread(runnable);
    thread4.start();

    }}

I've tried normally and it works fine. but on the lambda function it will not work properly. Thread is dying before the complete excution of threads. when return statement called it is automatically stopping threads.

Expected result
Hello
Hello
Hello
Hello


Actual Result 

Hello 
1 Answers

As people said in the comments, the problem is that you are not waiting for the threads to complete. You return from handleRequest() as soon as you're done starting threads. This tells Lambda that your execution is done, so it suspends your container before those threads have a chance to execute.

"Suspends your container" is the difference between running on Lambda and running locally. When you run locally the JVM actually exits, and it won't do so until all non-daemon threads have finished.

To ensure that all threads run, you need to call explicitly join them before returning from your handler function.

To help you understand how this works, you should also add some more debugging information (use System.err because it's unbuffered):

@Override
public String handleRequest(Object input, Context context) {

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.err.println("Hello from " + Thread.currentThread().getName());
        }
    };

    Thread thread1 = new Thread(runnable);
    thread1.start();
    Thread thread2 = new Thread(runnable);
    thread2.start();
    Thread thread3 = new Thread(runnable);
    thread3.start();
    Thread thread4 = new Thread(runnable);
    thread4.start();

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    System.err.println("handler function exiting");
}}
Related