How to prevent a javascript class getting initialized multiple times from different threads? I have a factory class outside AWS Lambda's handle method which will be loaded to AWS Lambda Execution environment. The "create" method inside the factory class can get called multiple times as more lambdas get spined up. The below code still can create multiple instances. For e.g, if there are multiple lambda executing this code simultaneously, this.map.get(name) can return undefined in many of the cases which will result in creation of multiple instances
const clientFactory = new ClientFactory();
export const handler = async (event) => {
const instance = clientFactory.getInstance("some name");
}
export class ClientFactory {
getInstance = (name: string) => {
let client = this.map.get(name);
if (!client) {
client = this.createClient(name);
await client.initialize();
this.map.set(client.getName(), client);
}
return client;
}
}
You mention multiple threads, and then you mention the Lambda function being called multiple times, but those two things are not the same. Each concurrent invocation/call of the Lambda function will be in a completely separate environment. You can make the assumption that concurrent calls to your Lambda function are happening on completely separate servers. Concurrent calls to your Lambda function do not happen in separate threads of a single environment.
Each invocation of your Lambda function runs in a complexly isolated environment. That environment will not receive another invocation until it has completely finished processing the current invocation.