【问题标题】:AWS lamda function not terminating the threadAWS lambda函数未终止线程
【发布时间】:2021-12-12 14:50:14
【问题描述】:

我编写了一个从 AWS lammda 函数执行的 java 代码。在我的用例中,我想在 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;
    }

}

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

【问题讨论】:

  • 首先,您的线程run 方法是一个繁忙的轮询 - 它会以零等待尽可能快地运行。这意味着没有那么多 CPU 可用于其他事情。接下来,您关闭线程,然后立即检查它是否已关闭。这可能需要一点时间,尤其是在线程中繁忙的轮询循环中。这段代码确实需要重构。

标签: java amazon-web-services aws-lambda thread-safety


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 2016-05-27
    • 2019-08-15
    • 1970-01-01
    • 2017-09-05
    • 2017-08-13
    • 1970-01-01
    • 2017-12-01
    • 2018-08-13
    相关资源
    最近更新 更多