1 // © 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 /* 4 **************************************************************************** 5 * Copyright (c) 2007-2015 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 volatile Reference<Map<K, V>> cacheRef = null; 23 private int type = ICUCache.SOFT; 24 private int capacity = DEFAULT_CAPACITY; 25 SimpleCache()26 public SimpleCache() { 27 } 28 SimpleCache(int cacheType)29 public SimpleCache(int cacheType) { 30 this(cacheType, DEFAULT_CAPACITY); 31 } 32 SimpleCache(int cacheType, int initialCapacity)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 @Override get(Object key)43 public V get(Object key) { 44 Reference<Map<K, V>> ref = cacheRef; 45 if (ref != null) { 46 Map<K, V> map = ref.get(); 47 if (map != null) { 48 return map.get(key); 49 } 50 } 51 return null; 52 } 53 54 @Override put(K key, V value)55 public void put(K key, V value) { 56 Reference<Map<K, V>> ref = cacheRef; 57 Map<K, V> map = null; 58 if (ref != null) { 59 map = ref.get(); 60 } 61 if (map == null) { 62 map = Collections.synchronizedMap(new HashMap<K, V>(capacity)); 63 if (type == ICUCache.WEAK) { 64 ref = new WeakReference<Map<K, V>>(map); 65 } else { 66 ref = new SoftReference<Map<K, V>>(map); 67 } 68 cacheRef = ref; 69 } 70 map.put(key, value); 71 } 72 73 @Override clear()74 public void clear() { 75 cacheRef = null; 76 } 77 78 } 79