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
11package android.icu.impl;
12
13import java.lang.ref.Reference;
14import java.lang.ref.SoftReference;
15import java.lang.ref.WeakReference;
16import java.util.Collections;
17import java.util.HashMap;
18import java.util.Map;
19
20/**
21 * @hide Only a subset of ICU is exposed in Android
22 */
23public 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
30    public SimpleCache() {
31    }
32
33    public SimpleCache(int cacheType) {
34        this(cacheType, DEFAULT_CAPACITY);
35    }
36
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
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
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
78    public void clear() {
79        cacheRef = null;
80    }
81
82}
83