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) 2010-2016, International Business Machines
6*   Corporation and others.  All Rights Reserved.
7*******************************************************************************
8*/
9package com.ibm.icu.impl;
10
11import java.util.concurrent.ConcurrentHashMap;
12
13/**
14 * Generic, thread-safe cache implementation, usually storing cached instances
15 * in {@link java.lang.ref.Reference}s via {@link CacheValue}s.
16 * To use, instantiate a subclass which implements the createInstance() method,
17 * and call get() with the key and the data. The get() call will use the data
18 * only if it needs to call createInstance(), otherwise the data is ignored.
19 *
20 * <p>When caching instances while the CacheValue "strength" is {@code SOFT},
21 * the Java runtime can later release these instances once they are not used any more at all.
22 * If such an instance is then requested again,
23 * the getInstance() method will call createInstance() again and reset the CacheValue.
24 * The cache holds on to its map of keys to CacheValues forever.
25 *
26 * <p>A value can be null if createInstance() returns null.
27 * In this case, it must do so consistently for the same key and data.
28 *
29 * @param <K> Cache lookup key type
30 * @param <V> Cache instance value type (must not be a CacheValue)
31 * @param <D> Data type for creating a new instance value
32 *
33 * @author Markus Scherer, Mark Davis
34 */
35public abstract class SoftCache<K, V, D> extends CacheBase<K, V, D> {
36    private ConcurrentHashMap<K, Object> map = new ConcurrentHashMap<K, Object>();
37
38    @SuppressWarnings("unchecked")
39    @Override
40    public final V getInstance(K key, D data) {
41        // We synchronize twice, once in the ConcurrentHashMap and
42        // once in valueRef.resetIfCleared(value),
43        // because we prefer the fine-granularity locking of the ConcurrentHashMap
44        // over coarser locking on the whole cache instance.
45        // We use a CacheValue (a second level of indirection) because
46        // ConcurrentHashMap.putIfAbsent() never replaces the key's value, and if it were
47        // a simple Reference we would not be able to reset its value after it has been cleared.
48        // (And ConcurrentHashMap.put() always replaces the value, which we don't want either.)
49        Object mapValue = map.get(key);
50        if(mapValue != null) {
51            if(!(mapValue instanceof CacheValue)) {
52                // The value was stored directly.
53                return (V)mapValue;
54            }
55            CacheValue<V> cv = (CacheValue<V>)mapValue;
56            if(cv.isNull()) {
57                return null;
58            }
59            V value = cv.get();
60            if(value != null) {
61                return value;
62            }
63            // The instance has been evicted, its Reference cleared.
64            // Create and set a new instance.
65            value = createInstance(key, data);
66            return cv.resetIfCleared(value);
67        } else /* valueRef == null */ {
68            // We had never cached an instance for this key.
69            V value = createInstance(key, data);
70            mapValue = (value != null && CacheValue.futureInstancesWillBeStrong()) ?
71                    value : CacheValue.getInstance(value);
72            mapValue = map.putIfAbsent(key, mapValue);
73            if(mapValue == null) {
74                // Normal "put": Our new value is now cached.
75                return value;
76            }
77            // Race condition: Another thread beat us to putting a CacheValue
78            // into the map. Return its value, but just in case the garbage collector
79            // was aggressive, we also offer our new instance for caching.
80            if(!(mapValue instanceof CacheValue)) {
81                // The value was stored directly.
82                return (V)mapValue;
83            }
84            CacheValue<V> cv = (CacheValue<V>)mapValue;
85            return cv.resetIfCleared(value);
86        }
87    }
88}
89