1 /*
2  * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */

15 package com.amazonaws.util;
16
17 import java.util.LinkedHashMap;
18 import java.util.Map.Entry;
19
20 import com.amazonaws.ResponseMetadata;
21 import com.amazonaws.annotation.SdkInternalApi;
22
23 /**
24  * Cache of response metadata for recently executed requests for diagnostic
25  * purposes. This cache has a max size and as entries are added, the oldest
26  * entry is aged out once the max size has been reached.
27  */

28 @SdkInternalApi
29 public class ResponseMetadataCache implements MetadataCache {
30     private final InternalCache internalCache;
31
32     /**
33      * Creates a new cache that will contain, at most the specified number of
34      * entries.
35      *
36      * @param maxEntries
37      *            The maximum size of this cache.
38      */

39     public ResponseMetadataCache(int maxEntries) {
40         internalCache = new InternalCache(maxEntries);
41     }
42
43     @Override
44     public synchronized void add(Object obj, ResponseMetadata metadata) {
45         if (obj == nullreturn;
46         internalCache.put(System.identityHashCode(obj), metadata);
47     }
48
49     @Override
50     public synchronized ResponseMetadata get(Object obj) {
51         // System.identityHashCode isn't guaranteed to be unique
52         // on all platforms, but should be reasonable enough to use
53         // for a few requests at a time.  We can always easily move
54         // to our own unique IDs if needed.
55         return internalCache.get(System.identityHashCode(obj));
56     }
57
58     /**
59      * Simple implementation of LinkedHashMap that overrides the
60      * <code>removeEldestEntry</code> method to turn LinkedHashMap into a
61      * FIFO cache that automatically evicts old entries.
62      */

63     private static final class InternalCache extends LinkedHashMap<Integer, ResponseMetadata> {
64         private static final long serialVersionUID = 1L;
65         private int maxSize;
66
67         InternalCache(int maxSize) {
68             super(maxSize);
69             this.maxSize = maxSize;
70         }
71
72         @Override
73         protected boolean removeEldestEntry(Entry<Integer,ResponseMetadata> eldest) {
74             return size() > maxSize;
75         }
76     }
77 }
78