001/* 002 * BioJava development code 003 * 004 * This code may be freely distributed and modified under the 005 * terms of the GNU Lesser General Public Licence. This should 006 * be distributed with the code. If you do not have a copy, 007 * see: 008 * 009 * http://www.gnu.org/copyleft/lesser.html 010 * 011 * Copyright for this code is held jointly by the individual 012 * authors. These should be listed in @author doc comments. 013 * 014 * For more information on the BioJava project and its aims, 015 * or to join the biojava-l mailing list, visit the home page 016 * at: 017 * 018 * http://www.biojava.org/ 019 * 020 */ 021 022package org.biojava.bio.seq.db; 023 024import java.io.IOException; 025import java.io.ObjectInputStream; 026import java.lang.ref.SoftReference; 027import java.util.HashMap; 028import java.util.Map; 029import java.util.Set; 030 031import org.biojava.bio.BioException; 032import org.biojava.bio.seq.Sequence; 033 034/** 035 * SequenceDB implementation that caches the results of another SequenceDB. 036 * 037 * @author Matthew Pocock 038 */ 039 040public class CachingSequenceDB extends SequenceDBWrapper { 041 private transient Map cache; 042 043 /** 044 * Create a new CachingSequenceDB that caches the sequences in parent. 045 * 046 * @param parent the SequenceDB to cache 047 */ 048 public CachingSequenceDB(SequenceDB parent) { 049 super(parent); 050 cache = new HashMap(); 051 } 052 053 public String getName() { 054 return getParent().getName(); 055 } 056 057 public Sequence getSequence(String id) throws BioException { 058 SoftReference ref = (SoftReference) cache.get(id); 059 Sequence seq; 060 if(ref == null) { 061 seq = getParent().getSequence(id); 062 cache.put(id, new SoftReference(seq)); 063 } else { 064 seq = (Sequence) ref.get(); 065 if(seq == null) { 066 seq = getParent().getSequence(id); 067 cache.put(id, new SoftReference(seq)); 068 } 069 } 070 return seq; 071 } 072 073 public Set ids() { 074 return getParent().ids(); 075 } 076 077 private void readObject(ObjectInputStream in) 078 throws IOException, ClassNotFoundException { 079 in.defaultReadObject(); 080 this.cache = new HashMap(); 081 } 082}