RTF
RTF

Reputation: 6504

Is it safe to declare an AWS Java SDK client object as static for concurrent use?

Is it safe to use the same client object for multiple requests concurrently with the AWS Java SDK. For example, if I have a web server handling multiple requests concurrently and one or more of the requests need access to DynamoDB, is it safe have a static client object for reads and writes with static accessor methods e.g.

public class DynamoDBManager {

    private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(CREDENTIALS);

    public static void doRead(String hashKey) {
        // use the client to read
    }

    public static void doWrite(MyData data) {
        // use the client to write
    }
}

...or should I drop the static modifiers on the methods and the client object so that every time a web server request needs access to the database it must instantiate the manager class to get it's own version of the client.

Will there be any concurrency issues or conflicts if the client object is static? I'm using DynamoDB here as an example, but I'm just as interested in the same scenario with an S3 client.

Upvotes: 8

Views: 4459

Answers (2)

Corey
Corey

Reputation: 511

To corroborate Julio's answer, they are thread safe and it is recommended to reuse the clients. Here are some links:

Java SDK v1

Client Lifecycle

Service clients in the SDK are thread-safe and, for best performance, you should treat them as long-lived objects. Each client has its own connection pool resource. Explicitly shut down clients when they are no longer needed to avoid resource leaks.

https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/creating-clients.html#client-lifecycle

Java SDK v2

Reuse an SDK client, if possible

Each SDK client maintains its own HTTP connection pool. A connection that already exists in the pool can be reused by a new request to cut down the time to establish a new connection. We recommend sharing a single instance of the client to avoid the overhead of having too many connection pools that aren't used effectively. All SDK clients are thread safe.

If you don't want to share a client instance, call close() on the instance to release the resources when the client is not needed.

https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/best-practices.html#bestpractice1

In addition, if you look at the Java SDK docs for clients you will see that they are now annotated with @ThreadSafe.

Upvotes: 0

Julio Faerman
Julio Faerman

Reputation: 13501

All the clients in the AWS SDK for Java are thread safe and you should to reuse client objects.

Upvotes: 14

Related Questions