1 package com.fasterxml.classmate.util;
2
3 import java.util.*;
4
5 import com.fasterxml.classmate.ResolvedType;
6
7 /**
8  * Simple cache used for storing up to specified number of most recently accessed
9  * {@link ResolvedType} instances. Uses "least-recently used" eviction algorithm
10  * (via {@link LinkedHashMap} used internally) which optimized retention, but
11  * requires full synchronization as read operation also has to modify internal state
12  * to maintain LRU aspects.
13  * This means that it works well in optimizing access patterns, by keeping most recently
14  * accessed types in cache, but may not well work well for highly concurrent cases due
15  * to synchronization overhead.
16  *<p>
17  * Like all {@link ResolvedTypeCache} implementations,
18  * access is thread-safe and caller need not (and should not) use additional synchronization.
19  *<p>
20  *
21  * @see ConcurrentTypeCache
22  *
23  * @since 1.4
24  */

25 public class LRUTypeCache extends ResolvedTypeCache
26 {
27     private static final long serialVersionUID = 1L;
28
29     protected final int _maxEntries;
30
31     protected final transient CacheMap _map;
32
33     public LRUTypeCache(int maxEntries) {
34         _map = new CacheMap(maxEntries);
35         _maxEntries = maxEntries;
36     }
37
38     // For JDK serialization: have to re-construct backing Map since it is NOT serialized
39     Object readResolve() {
40         return new LRUTypeCache(_maxEntries);
41     }
42
43     @Override
44     public synchronized ResolvedType find(ResolvedTypeKey key) {
45         if (key == null) {
46             throw new IllegalArgumentException("Null key not allowed");
47         }
48         return _map.get(key);
49     }
50
51     @Override
52     public synchronized int size() {
53         return _map.size();
54     }
55     
56     @Override
57     public synchronized void put(ResolvedTypeKey key, ResolvedType type) {
58         if (key == null) {
59             throw new IllegalArgumentException("Null key not allowed");
60         }
61         _map.put(key, type);
62     }
63
64     /*
65     /**********************************************************************
66     /* Helper classes
67     /**********************************************************************
68      */

69
70     /**
71      * Simple sub-class to get LRU cache
72      */

73     @SuppressWarnings("serial")
74     private final static class CacheMap
75         extends LinkedHashMap<ResolvedTypeKey, ResolvedType>
76     {
77         protected final int _maxEntries;
78         
79         public CacheMap(int maxEntries) {
80             _maxEntries = maxEntries;
81         }
82
83         @Override
84         protected boolean removeEldestEntry(Map.Entry<ResolvedTypeKey, ResolvedType> eldest) {
85             return size() > _maxEntries;
86         }
87     }
88 }
89