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