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