1 package org.apache.commons.ognl.internal;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 /*
23 * $Id: ConcurrentHashMapCache.java 1194950 2011-10-29 17:52:20Z mcucchiara $
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 }