Kailash Panwar
Kailash Panwar

Reputation: 91

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.

Upvotes: 3

Views: 5573

Answers (3)

BAD_SEED
BAD_SEED

Reputation: 5056

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.

Upvotes: 4

Evdzhan Mustafa
Evdzhan Mustafa

Reputation: 3735

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.

Upvotes: 5

nickolay.laptev
nickolay.laptev

Reputation: 2565

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.

Upvotes: 2

Related Questions