Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using AWS Lambda with Java programming language, due to some requirement I have to give sleep in my lambda function for 2-3 or in some cases upto 12 seconds, is it good idea to put Thread.sleep() in lambda function or it has any technical consequences.

like image 252
Kailash Panwar Avatar asked Feb 17 '26 15:02

Kailash Panwar


2 Answers

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. E.g. 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. E.g. 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.

like image 81
Evdzhan Mustafa Avatar answered Feb 19 '26 05:02

Evdzhan Mustafa


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.

like image 33
BAD_SEED Avatar answered Feb 19 '26 05:02

BAD_SEED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!