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.util.HashMap;
22 import org.simantics.utils.datastructures.disposable.AbstractDisposable;
25 * CachedProvider provides values and stores the results in a cache.
26 * Cached values must be explicitly released with clear, retain or remove.
27 * Values are held with strong references.
30 * @param <V> the value
32 public class CachedMapProvider<K, V> extends AbstractDisposable implements IMapProvider<K, V> {
34 private Map<K, V> cache;
36 private final IMapProvider<K, V> provider;
39 * Constructs new strong cache
41 * @param provider provider of values
43 public CachedMapProvider(IMapProvider<K, V> provider)
45 assert(provider!=null);
46 this.provider = provider;
47 this.cache = new HashMap<K, V>();
51 * Constructs new strong cache
53 * @param provider provider of values
54 * @param cacheMap the map to use
56 public CachedMapProvider(IMapProvider<K, V> provider, Map<K, V> cacheMap)
58 assert(provider!=null);
59 this.provider = provider;
60 this.cache = cacheMap;
64 public synchronized V get(K key) {
66 V value = cache.get(key);
67 if (value!=null) return value;
68 value = provider.get(key);
70 cache.put(key, value);
74 public synchronized void clear()
79 public synchronized void retain(Set<K> keys)
81 cache.keySet().retainAll(keys);
84 public synchronized void remove(Set<K> keys)
86 cache.keySet().removeAll(keys);
89 public synchronized void load(Set<K> keys)
95 public synchronized void addAll(CachedMapProvider<K, V> anotherCache)
98 cache.putAll(anotherCache.cache);
101 public IMapProvider<K, V> getProvider() {
105 public synchronized Map<K, V> getAll()
108 return new HashMap<K, V>(cache);
112 protected void doDispose() {