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 import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
26
27 import java.util.concurrent.ConcurrentHashMap;
28
29 public class ConcurrentHashMapCache<K, V>
30 implements Cache<K, V>
31 {
32 private ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<K, V>();
33
34 private CacheEntryFactory<K, V> cacheEntryFactory;
35
36 public ConcurrentHashMapCache()
37 {
38 }
39
40 public ConcurrentHashMapCache( CacheEntryFactory<K, V> cacheEntryFactory )
41 {
42 this.cacheEntryFactory = cacheEntryFactory;
43 }
44
45 public void clear()
46 {
47 cache.clear();
48 }
49
50 public int getSize()
51 {
52 return cache.size();
53 }
54
55 public V get( K key )
56 throws CacheException
57 {
58 V v = cache.get( key );
59 if ( shouldCreate( cacheEntryFactory, v ) )
60 {
61 return put( key, cacheEntryFactory.create( key ) );
62 }
63 return v;
64 }
65
66 protected boolean shouldCreate( CacheEntryFactory<K, V> cacheEntryFactory, V v )
67 throws CacheException
68 {
69 if ( cacheEntryFactory != null )
70 {
71 if ( v == null )
72 {
73 return true;
74 }
75 }
76 return false;
77 }
78
79 public V put( K key, V value )
80 {
81 V collision = cache.putIfAbsent( key, value );
82 if ( collision != null )
83 {
84 return collision;
85 }
86 return value;
87 }
88
89 public boolean contains( K key )
90 {
91 return this.cache.contains( key );
92 }
93 }