How to close AWS connection if there is no such key in the query

amazon-s3, amazon-web-services, aws-sdk, java, sdk

Solution

If you use Java 1.7, you can use try-with-resouce block. The object will be closed automatically when leaving the block.

GetObjectRequest req = new GetObjectRequest(bucketName, fileName);
try(S3Object object = s3Client.getObject(req)) {
    ...
} catch(AmazonServiceException e) {
    if(e.getErrorCode().equals("NoSuchKey"));
}

If you use Java 1.6 or prior version, you need to do it in finally block

S3Object object = null;
GetObjectRequest req = new GetObjectRequest(bucketName, fileName);
try {
    object = s3Client.getObject(req))
    ...
} catch(AmazonServiceException e) {
    if(e.getErrorCode().equals("NoSuchKey"));
} finally {
    if (object != null) {
        object.close();
    }
}

Problem

I'm using AWS java SDK to upload file on AWS Management Console's Bucket. However, if there is no such file online at first time when I try to get access to it, my code will catch the exception (NoSuchKey). Then I want to close the connection. The problem is I don't have any reference to close that connection because of the exception(The original reference will be null). Here is my code: ``` S3Object object = null; GetObjectRequest req = new GetObjectRequest(bucketName, fileName); try{ logconfig(); object = s3Client.getObject(req); ... catch(AmazonServiceException e){ if(e.getErrorCode().equals("NoSuchKey")) ``` I was trying to use "object" as a reference to close the connection between my eclipse and Aws, but apparently "object" is null when the exception happened. Can anyone tell me how to do it? Furthermore, because I can't close the connection, my console will have this warning every 60 seconds: ``` 8351167 [java-sdk-http-connection-reaper] DEBUG org.apache.http.impl.conn.PoolingClientConnectionManager - Closing connections idle longer than 60 SECONDS ```

Original source