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