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