java AWS lambda函数未终止线程

8fsztsew  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(127)

我已经写了一个Java代码从AWS lambda函数执行。在我的用例中,我想在lambda函数终止之前写一些通用日志。为了实现这一点,我创建了一个新线程,它监视lambda函数的RemainingTimeInMillis。如果它达到了一些限制,我将写一些通用消息。现在我的问题是,即使我终止了一个线程,它也不会终止。

public class Lambda implements RequestHandler<Map<String, String>, String> {
public String handleRequests(Map<String, String> parameters, Context context) {
    LambdaTimeoutCheck thread = null;
    thread = new LambdaTimeoutCheck(context, "applicationName");
        thread.setName(threadname);
        thread.setStopTimeout(true);
        thread.start();

        /* remaining function logic  */
        System.out.println("Lambda function starts"+thread.isAlive());

        thread.shutdown();

        System.out.println("Lambda function ends"+thread.isAlive());
        return "success"
}


package com.pearson.autobahn.autobahnsdkheartbeat;

import com.amazonaws.services.lambda.runtime.Context;

public class LambdaTimeoutCheck extends Thread {

    private Context context;

    private String applicationName;

    private boolean isStopTimeout;

    public LambdaTimeoutCheck(Context context, String applicationName) {
        this.context = context;
        this.applicationName = applicationName;
    }

    @Override
    public void run() {
        
        while (isStopTimeout()) {

            if (context.getRemainingTimeInMillis() <= 1000) {
                
                context.getLogger().log("Request ID: " + context.getAwsRequestId() + " " + applicationName
                        + " function execution about to Timeout");
                setStopTimeout(false);
            } 
            }

        }
    }

    
    public void shutdown() {

        this.setStopTimeout(false);

    }

    
    public boolean isStopTimeout() {
        return isStopTimeout;
    }

    public void setStopTimeout(boolean isStopTimeout) {
        this.isStopTimeout = isStopTimeout;
    }

}

isAlive()总是正确的,即使我关闭了一个线程。请帮助我解决这个问题。

c3frrgcw

c3frrgcw1#

就像任何Java程序一样:如果你的主线程需要等待另一个线程完成,你应该在子线程上调用join()

相关问题