1 /*******************************************************************************
\r
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
\r
3 * in Industry THTH ry.
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
14 * @author Toni Kalajainen
\r
16 package org.simantics.utils.datastructures.cache;
\r
18 import java.lang.ref.WeakReference;
\r
19 import java.util.HashMap;
\r
20 import java.util.Map;
\r
23 * WeakCachedProvider provides values and stores the results in a cache.
\r
24 * Cached values are held with weak references. Values are removed
\r
25 * automatically as they are disposed.
\r
27 * Keys are referenced with strong references.
\r
29 * @param <K> key type
\r
30 * @param <V> value type
\r
32 public class WeakCachedMapProvider<K, V> implements IMapProvider<K, V> {
\r
34 private Map<K, WeakReference<V>> cache =
\r
35 new HashMap<K, WeakReference<V>>();
\r
37 private final IMapProvider<K, V> provider;
\r
40 * Constructs new weak cache.
\r
42 * @param provider provider of values
\r
44 public WeakCachedMapProvider(IMapProvider<K, V> provider)
\r
46 assert(provider!=null);
\r
47 this.provider = provider;
\r
51 public synchronized V get(K key)
\r
53 WeakReference<V> ref = cache.get(key);
\r
55 V result = ref.get();
\r
56 if (result!=null) return result;
\r
60 V value = provider.get(key);
\r
61 assert(value!=null);
\r
63 ref = new WeakReference<V>(value);
\r
64 cache.put(key, ref);
\r
69 * Release all weak references
\r
71 public synchronized void clear()
\r