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: HashMapCache.java 1194954 2011-10-29 18:00:27Z mcucchiara $
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 }