Inside AWS lambda function (written in Java) I want to use AsyncHttpClient (https://github.com/AsyncHttpClient/async-http-client). Unfortunately it takes around 500 ms to create an instance of this object.. (but I still like it, please don't advice me to change the http client).
I was considering creating AsyncHttpClient in static initialization block. So maybe it will be executed once by AWS and than the snapshot would be cloned for the every AWS Lambda execution. Am I correct ?
When static block are executed in AWS Lambda ?
Thank you for help
There is no "snapshot" taken of your Lambda execution environment, ever. There is however a concept of container reuse. A static initialization block will be called when the function runs for the first time in a new container, and each subsequent Lambda execution that is sent to that container will be able to skip the initialization step. Each time Lambda spins up a new container for your Lambda function that initialization work will need to happen again.
I suggest reading this post on the AWS blog about Lambda container reuse.
As Mark B explained, there is no such thing as a 'snapshot'.
AWS starts an execution context the first time your Lambda is called and then reuses it for the next requests. However, this is not guaranteed. AWS may shut down this context at any time, or create others to scale your Lambda in case your of heavy load.
An execution context consists of the container, the JVM, and a Singleton instance of the Java class where your handler function is defined.
Therefore, I would not recommend doing any "one-time" initialization in a static block, but instead in the constructor of your class. This will greatly improve the testability of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With