1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
14 * @author Toni Kalajainen
16 package org.simantics.utils.datastructures.cache;
18 import java.lang.ref.WeakReference;
19 import java.util.HashMap;
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.
27 * Keys are referenced with strong references.
30 * @param <V> value type
32 public class WeakCachedMapProvider<K, V> implements IMapProvider<K, V> {
34 private Map<K, WeakReference<V>> cache =
35 new HashMap<K, WeakReference<V>>();
37 private final IMapProvider<K, V> provider;
40 * Constructs new weak cache.
42 * @param provider provider of values
44 public WeakCachedMapProvider(IMapProvider<K, V> provider)
46 assert(provider!=null);
47 this.provider = provider;
51 public synchronized V get(K key)
53 WeakReference<V> ref = cache.get(key);
56 if (result!=null) return result;
60 V value = provider.get(key);
63 ref = new WeakReference<V>(value);
69 * Release all weak references
71 public synchronized void clear()