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
12 package org.simantics.utils.datastructures.cache;
\r
14 import java.lang.ref.SoftReference;
\r
17 * Caches the value provided by provider until the value has been garbage collected.
\r
19 * Cached IProvider provides the same instance as long as it is in memory.
\r
21 * Cached version is equal to original in hashCode/equals wise.
\r
23 * @author Toni Kalajainen
\r
25 public class SoftCachedProvider<V> implements IProvider<V> {
\r
27 public static final <V> IProvider<V> cache(IProvider<V> provider)
\r
29 if (provider instanceof SoftCachedProvider<?>)
\r
31 return new SoftCachedProvider<V>(provider);
\r
34 IProvider<V> provider;
\r
35 SoftReference<V> ref;
\r
37 SoftCachedProvider(IProvider<V> orig)
\r
39 this.provider = orig;
\r
43 public synchronized V get() throws ProvisionException {
\r
46 if (x==null) ref=null;
\r
49 V x = provider.get();
\r
50 ref = new SoftReference<V>(x);
\r
55 public int hashCode() {
\r
56 return provider.hashCode();
\r
60 public boolean equals(Object obj) {
\r
61 return provider.equals(obj);
\r