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.utils.cache; 023 024import java.lang.ref.WeakReference; 025import java.util.LinkedList; 026import java.util.List; 027 028/** 029 * Cache which stores up to <code>limit</code> Objects. 030 * 031 * @since 1.1 032 * @author Thomas Down 033 */ 034 035public class FixedSizeCache implements Cache { 036 private List objects; 037 private int sizeLimit; 038 039 { 040 objects = new LinkedList(); 041 } 042 043 public FixedSizeCache(int limit) { 044 sizeLimit = limit; 045 } 046 047 public CacheReference makeReference(Object o) { 048 CacheReference cr = new FixedSizeCacheReference(o); 049 objects.add(new WeakReference(cr)); 050 while (objects.size() > sizeLimit) { 051 CacheReference old = (CacheReference) ((WeakReference) objects.remove(0)).get(); 052 if (old != null) { 053 old.clear(); 054 } 055 } 056 057 return cr; 058 } 059 060 public int getLimit() { 061 return sizeLimit; 062 } 063 064 public void setLimit(int limit) { 065 this.sizeLimit = limit; 066 } 067 068 private class FixedSizeCacheReference implements CacheReference { 069 private Object o; 070 071 private FixedSizeCacheReference(Object o) { 072 this.o = o; 073 } 074 075 public Object get() { 076 return o; 077 } 078 079 public void clear() { 080 o = null; 081 } 082 } 083} 084