View Javadoc

1   /*
2    *  Copyright 2004 David C. Brown
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.ashkay.strategies;
17  
18  import java.lang.ref.Reference;
19  import java.lang.ref.ReferenceQueue;
20  import java.util.IdentityHashMap;
21  import java.util.Map;
22  
23  import net.sf.ashkay.CacheEntry;
24  import net.sf.ashkay.CachingStrategy;
25  
26  
27  /***
28   * A Soft Reference caching strategy uses soft references to store objects in
29   * the cache. Soft references do not prevent the garbage collection of the
30   * objects.
31   *
32   * @author <a href="mailto:bangroot@users.sf.net">Dave Brown</a>
33   */
34  
35  public class SoftReferenceCachingStrategy implements CachingStrategy
36  {
37  	private Map entryMap = new IdentityHashMap();
38  	private ReferenceQueue queue = new ReferenceQueue();
39  
40  	public CacheEntry prepare(CacheEntry entry)
41  	{
42  		checkQueue();
43  
44  		SoftReferenceCacheEntry theEntry = new SoftReferenceCacheEntry(entry, queue);
45  		entryMap.put(theEntry.getEntryReference(), theEntry);
46  		return theEntry;
47  	}
48  
49  
50  	public boolean validate(CacheEntry entry)
51  	{
52  		checkQueue();
53  
54  		boolean val = true;
55  		if (entry.getEntryObject() == null)
56  		{
57  			val = false;
58  		}
59  
60  		return val;
61  	}
62  
63  	private void checkQueue()
64  	{
65  		Reference ref = queue.poll();
66  		while (ref != null)
67  		{
68  			CacheEntry entryToClear = (CacheEntry) entryMap.get(ref);
69  			if (entryToClear != null)
70  			{
71  				entryToClear.getCache().evict(entryToClear.getEntryKey());
72  				entryMap.remove(ref);
73  			}
74  			ref = queue.poll();
75  		}
76  	}
77  }