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