View Javadoc

1   /***
2    * Created on 2005-02-07
3    * @author Philippe Lefebvre <philippe.lefebvre@gmail.com>
4    */
5   package net.sf.xtract;
6   
7   import java.io.File;
8   import java.util.LinkedList;
9   import java.util.Map;
10  import java.util.concurrent.ExecutionException;
11  import java.util.concurrent.Future;
12  
13  import net.sf.xtract.caching.LazyEntry;
14  import net.sf.xtract.util.SoftHashMap;
15  
16  import org.w3c.dom.Document;
17  
18  /***
19   * @TODO Document DOMCache
20   */
21  public class DocumentCache {
22  
23    private final Map<File, Entry> mHashMap;
24    private final LinkedList<File> mMRU;
25    private final int mMaxSize;
26    
27    public DocumentCache() {
28      this(Integer.MAX_VALUE);
29    }
30    
31    public DocumentCache(int pMaxSize) {
32      mHashMap = new SoftHashMap<File, Entry>();
33      mMRU = new LinkedList<File>();
34      mMaxSize = pMaxSize;
35    }
36    
37    public Document getDocument(File pFile) throws InterruptedException, ExecutionException {
38      Document lResult;
39      Entry lEntry;
40      Future<Entry> lFuture;
41      
42      // Obtain Entry
43      synchronized (mHashMap) {
44        lEntry = mHashMap.get(pFile);
45        if (lEntry == null || pFile.lastModified() > lEntry.getTimestamp()) {
46          lEntry = new LazyEntry(pFile);
47          mHashMap.put(pFile, lEntry);
48        }
49      }
50       
51      lResult = lEntry.getDocument();
52        
53      // Update MRU
54      mMRU.remove(pFile);
55      mMRU.add(pFile);
56      
57      assert(lResult != null);
58      return lResult;    
59    }
60    
61    public interface Entry {
62      public File getFile() throws InterruptedException, ExecutionException;
63      public Document getDocument() throws InterruptedException, ExecutionException;
64      public long getTimestamp() throws InterruptedException, ExecutionException;
65    }
66    
67  }