简体   繁体   中英

Why Multithreading is not working perfectly in AWS Lambda function?

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 

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");
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM