001 package org.apache.commons.ognl.internal; 002 003 /* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022 /* 023 * $Id: HashMapCache.java 1194954 2011-10-29 18:00:27Z mcucchiara $ 024 */ 025 026 import org.apache.commons.ognl.internal.entry.CacheEntryFactory; 027 028 import java.util.HashMap; 029 import java.util.Map; 030 031 public class HashMapCache<K, V> 032 implements Cache<K, V> 033 { 034 private final Map<K, V> cache = new HashMap<K, V>( 512 ); 035 036 private CacheEntryFactory<K, V> cacheEntryFactory; 037 038 public HashMapCache( CacheEntryFactory<K, V> cacheEntryFactory ) 039 { 040 this.cacheEntryFactory = cacheEntryFactory; 041 } 042 043 public void clear() 044 { 045 synchronized ( cache ) 046 { 047 cache.clear(); 048 } 049 } 050 051 public int getSize() 052 { 053 synchronized ( cache ) 054 { 055 return cache.size(); 056 } 057 } 058 059 public V get( K key ) 060 throws CacheException 061 { 062 V v = cache.get( key ); 063 if ( shouldCreate( cacheEntryFactory, v ) ) 064 { 065 synchronized ( cache ) 066 { 067 v = cache.get( key ); 068 if ( v != null ) 069 { 070 return v; 071 } 072 return put( key, cacheEntryFactory.create( key ) ); 073 } 074 } 075 return v; 076 } 077 078 protected boolean shouldCreate( CacheEntryFactory<K, V> cacheEntryFactory, V v ) 079 throws CacheException 080 { 081 if ( cacheEntryFactory != null ) 082 { 083 if ( v == null ) 084 { 085 return true; 086 } 087 } 088 return false; 089 } 090 091 public V put( K key, V value ) 092 { 093 synchronized ( cache ) 094 { 095 cache.put( key, value ); 096 return value; 097 } 098 } 099 100 101 public boolean contains( K key ) 102 { 103 return this.cache.containsKey( key ); 104 } 105 }