]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.datastructures/src/org/simantics/utils/datastructures/cache/SoftCachedProvider.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.utils.datastructures / src / org / simantics / utils / datastructures / cache / SoftCachedProvider.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.utils.datastructures.cache;
13
14 import java.lang.ref.SoftReference;
15
16 /**
17  * Caches the value provided by provider until the value has been garbage collected.
18  * <p>
19  * Cached IProvider provides the same instance as long as it is in memory.
20  * <p>
21  * Cached version is equal to original in hashCode/equals wise.
22  * 
23  * @author Toni Kalajainen
24  */
25 public class SoftCachedProvider<V> implements IProvider<V> {
26
27     public static final <V> IProvider<V> cache(IProvider<V> provider)
28     {
29         if (provider instanceof SoftCachedProvider<?>)
30             return provider;
31         return new SoftCachedProvider<V>(provider);
32     }
33
34     IProvider<V> provider;
35     SoftReference<V> ref;
36
37     SoftCachedProvider(IProvider<V> orig)
38     {
39         this.provider = orig;
40     }
41
42     @Override
43     public synchronized V get() throws ProvisionException {
44         if (ref!=null) {
45             V x = ref.get();
46             if (x==null) ref=null;
47             else return x;
48         }
49         V x = provider.get();
50         ref = new SoftReference<V>(x);
51         return x;
52     }
53
54     @Override
55     public int hashCode() {
56         return provider.hashCode();
57     }
58
59     @Override
60     public boolean equals(Object obj) {
61         return provider.equals(obj);
62     }
63
64 }