]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-52_1/main/classes/core/src/com/ibm/icu/impl/SimpleCache.java
Clean up imports.
[Dictionary.git] / jars / icu4j-52_1 / main / classes / core / src / com / ibm / icu / impl / SimpleCache.java
1 /*
2  ****************************************************************************
3  * Copyright (c) 2007-2009 International Business Machines Corporation and  *
4  * others.  All rights reserved.                                            *
5  ****************************************************************************
6  */
7
8 package com.ibm.icu.impl;
9
10 import java.lang.ref.Reference;
11 import java.lang.ref.SoftReference;
12 import java.lang.ref.WeakReference;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.Map;
16
17 public class SimpleCache<K, V> implements ICUCache<K, V> {
18     private static final int DEFAULT_CAPACITY = 16;
19
20     private Reference<Map<K, V>> cacheRef = null;
21     private int type = ICUCache.SOFT;
22     private int capacity = DEFAULT_CAPACITY;
23
24     public SimpleCache() {
25     }
26
27     public SimpleCache(int cacheType) {
28         this(cacheType, DEFAULT_CAPACITY);
29     }
30
31     public SimpleCache(int cacheType, int initialCapacity) {
32         if (cacheType == ICUCache.WEAK) {
33             type = cacheType;
34         }
35         if (initialCapacity > 0) {
36             capacity = initialCapacity;
37         }
38     }
39
40     public V get(Object key) {
41         Reference<Map<K, V>> ref = cacheRef;
42         if (ref != null) {
43             Map<K, V> map = ref.get();
44             if (map != null) {
45                 return map.get(key);
46             }
47         }
48         return null;
49     }
50
51     public void put(K key, V value) {
52         Reference<Map<K, V>> ref = cacheRef;
53         Map<K, V> map = null;
54         if (ref != null) {
55             map = ref.get();
56         }
57         if (map == null) {
58             map = Collections.synchronizedMap(new HashMap<K, V>(capacity));
59             if (type == ICUCache.WEAK) {
60                 ref = new WeakReference<Map<K, V>>(map);
61             } else {
62                 ref = new SoftReference<Map<K, V>>(map);
63             }
64             cacheRef = ref;
65         }
66         map.put(key, value);
67     }
68
69     public void clear() {
70         cacheRef = null;
71     }
72
73 }