]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.datastructures/src/org/simantics/utils/datastructures/cache/WeakCachedMapProvider.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.utils.datastructures / src / org / simantics / utils / datastructures / cache / WeakCachedMapProvider.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 /*
13  *
14  * @author Toni Kalajainen
15  */
16 package org.simantics.utils.datastructures.cache;
17
18 import java.lang.ref.WeakReference;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 /**
23  * WeakCachedProvider provides values and stores the results in a cache.
24  * Cached values are held with weak references. Values are removed
25  * automatically as they are disposed.
26  *
27  * Keys are referenced with strong references.
28  *
29  * @param <K> key type
30  * @param <V> value type
31  */
32 public class WeakCachedMapProvider<K, V> implements IMapProvider<K, V> {
33
34         private Map<K, WeakReference<V>> cache = 
35                 new HashMap<K, WeakReference<V>>();
36         
37         private final IMapProvider<K, V> provider;
38         
39         /**
40          * Constructs new weak cache.
41          * 
42          * @param provider provider of values 
43          */
44         public WeakCachedMapProvider(IMapProvider<K, V> provider)
45         {
46                 assert(provider!=null);
47                 this.provider = provider;
48         }       
49         
50         @Override
51         public synchronized V get(K key) 
52         {
53                 WeakReference<V> ref = cache.get(key);
54                 if (ref!=null) {
55                         V result = ref.get();
56                         if (result!=null) return result;
57                         cache.remove(ref);
58                 }
59                 
60                 V value = provider.get(key);
61                 assert(value!=null);
62                 
63                 ref = new WeakReference<V>(value);
64                 cache.put(key, ref);
65                 return value;           
66         }
67         
68         /**
69          * Release all weak references
70          */
71         public synchronized void clear()
72         {
73                 cache.clear();
74         }       
75
76 }