1 package org.apache.commons.ognl.internal;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
27
28 import java.util.HashMap;
29 import java.util.Map;
30
31 public class HashMapCache<K, V>
32 implements Cache<K, V>
33 {
34 private final Map<K, V> cache = new HashMap<K, V>( 512 );
35
36 private CacheEntryFactory<K, V> cacheEntryFactory;
37
38 public HashMapCache( CacheEntryFactory<K, V> cacheEntryFactory )
39 {
40 this.cacheEntryFactory = cacheEntryFactory;
41 }
42
43 public void clear()
44 {
45 synchronized ( cache )
46 {
47 cache.clear();
48 }
49 }
50
51 public int getSize()
52 {
53 synchronized ( cache )
54 {
55 return cache.size();
56 }
57 }
58
59 public V get( K key )
60 throws CacheException
61 {
62 V v = cache.get( key );
63 if ( shouldCreate( cacheEntryFactory, v ) )
64 {
65 synchronized ( cache )
66 {
67 v = cache.get( key );
68 if ( v != null )
69 {
70 return v;
71 }
72 return put( key, cacheEntryFactory.create( key ) );
73 }
74 }
75 return v;
76 }
77
78 protected boolean shouldCreate( CacheEntryFactory<K, V> cacheEntryFactory, V v )
79 throws CacheException
80 {
81 if ( cacheEntryFactory != null )
82 {
83 if ( v == null )
84 {
85 return true;
86 }
87 }
88 return false;
89 }
90
91 public V put( K key, V value )
92 {
93 synchronized ( cache )
94 {
95 cache.put( key, value );
96 return value;
97 }
98 }
99
100
101 public boolean contains( K key )
102 {
103 return this.cache.containsKey( key );
104 }
105 }