简体   繁体   中英

Is it good idea to use Thread.sleep in AWS lambda java

我将 AWS Lambda 与 Java 编程语言一起使用,由于某些要求,我必须在我的 lambda 函数中休眠 2-3 秒或在某些情况下最多 12 秒,将 Thread.sleep() 放入 lambda 函数或它有任何技术后果。

There are few cases in which doing Thread.sleep is justified.

  • Polling every few seconds and checking if certain status, which is not in control of your code has changed. Eg think of checking if remote process somewhere has finished.
  • You want to mock certain piece of code, so that it "takes" more time than it actually does.
  • Throttling down piece of code that does multiple operations per second. Eg requesting multiple resources from a remote server, but throttling down your requests so that you don't overload it.

I'm sure there are quite a few more justifiable reasons. Don't be afraid to sleep your code. Make sure you're sleeping for a justifiable reason. Also make sure your thread model, in which you indeed need to sleep in your code, does not cause deadlocks .

Note that running in AWS Lambda you should optimize your sleeps to as little amount as possible, as you pay for that sweet, sweet CPU time.

If your Lambda use a high amount of memory would be better (and cheaper) to start two different Lambda than wait for 12 seconds.

If you have a sort of workflow, or you need to wait for a specific condition you could evaluate the introduction of AWS Step Functions or (maybe better) send context to an SQS queue with visibility timeout set to twelve second. In this way, the second lambda will wait, at least, 12 seconds before starts.

Basically you can do whatever you want, in this case you will just pay more :-)

The whole idea of Lambda function is to have a function that takes input and produces output and have a single responsibility, similar to plain old functions.

Let's think why you need to use Thread#sleep :

  1. You perform action #1.
  2. Wait until this action is completed.
  3. Perform action #2.

These are 3 different responsibilities. It's too much for any function, including Lambda :-)
Both actions can be separate Lambda functions. With recent addition of Destination, your Lambda #1 can trigger Lambda #2.
In this case there is no need in polling at all.

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