1 // 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html#License 3 /* 4 **************************************************************************** 5 * Copyright (c) 2007-2011 International Business Machines Corporation and * 6 * others. All rights reserved. * 7 **************************************************************************** 8 */ 9 10 package com.ibm.icu.impl; 11 12 import java.lang.ref.Reference; 13 import java.lang.ref.SoftReference; 14 import java.lang.ref.WeakReference; 15 import java.util.Collections; 16 import java.util.HashMap; 17 import java.util.Map; 18 19 public class SimpleCache<K, V> implements ICUCache<K, V> { 20 private static final int DEFAULT_CAPACITY = 16; 21 22 private Reference<Map<K, V>> cacheRef = null; 23 private int type = ICUCache.SOFT; 24 private int capacity = DEFAULT_CAPACITY; 25 26 public SimpleCache() { 27 } 28 29 public SimpleCache(int cacheType) { 30 this(cacheType, DEFAULT_CAPACITY); 31 } 32 33 public SimpleCache(int cacheType, int initialCapacity) { 34 if (cacheType == ICUCache.WEAK) { 35 type = cacheType; 36 } 37 if (initialCapacity > 0) { 38 capacity = initialCapacity; 39 } 40 } 41 42 public V get(Object key) { 43 Reference<Map<K, V>> ref = cacheRef; 44 if (ref != null) { 45 Map<K, V> map = ref.get(); 46 if (map != null) { 47 return map.get(key); 48 } 49 } 50 return null; 51 } 52 53 public void put(K key, V value) { 54 Reference<Map<K, V>> ref = cacheRef; 55 Map<K, V> map = null; 56 if (ref != null) { 57 map = ref.get(); 58 } 59 if (map == null) { 60 map = Collections.synchronizedMap(new HashMap<K, V>(capacity)); 61 if (type == ICUCache.WEAK) { 62 ref = new WeakReference<Map<K, V>>(map); 63 } else { 64 ref = new SoftReference<Map<K, V>>(map); 65 } 66 cacheRef = ref; 67 } 68 map.put(key, value); 69 } 70 71 public void clear() { 72 cacheRef = null; 73 } 74 75 } 76