Mega Code Archive

 
Categories / Java / Collections Data Structure
 

Soft HashMap

/*  * dbXML - Native XML Database  * Copyright (C) 1999-2004  The dbXML Group, L.L.C.  *  * This program is free software; you can redistribute it and/or  * modify it under the terms of the GNU General Public License  * as published by the Free Software Foundation; either version 2  * of the License, or (at your option) any later version.  *  * This program is distributed in the hope that it will be useful,  * but WITHOUT ANY WARRANTY; without even the implied warranty of  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  * GNU General Public License for more details.  *  * You should have received a copy of the GNU General Public License  * along with this program; if not, write to the Free Software  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  *  * $Id: SoftHashMap.java,v 1.2 2004/02/12 00:17:58 bradford Exp $  */ import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.AbstractMap; import java.util.HashMap; import java.util.Map; import java.util.Set; /**  * SoftHashMap  */ public final class SoftHashMap extends AbstractMap {    private Map hash = new HashMap();    private final ReferenceQueue queue = new ReferenceQueue();    public SoftHashMap() {    }    public Object get(Object key) {       Object res = null;       SoftReference sr = (SoftReference)hash.get(key);       if ( sr != null ) {          res = sr.get();          if ( res == null )             hash.remove(key);       }       return res;    }    private void processQueue() {       for ( ;; ) {          SoftValue sv = (SoftValue)queue.poll();          if ( sv != null )             hash.remove(sv.key);          else             return;       }    }    public Object put(Object key, Object value) {       processQueue();       return hash.put(key, new SoftValue(value, key, queue));    }    public Object remove(Object key) {       processQueue();       return hash.remove(key);    }    public void clear() {       processQueue();       hash.clear();    }    public int size() {       processQueue();       return hash.size();    }    public Set entrySet() {       /** @todo Figure this out */       throw new UnsupportedOperationException();    }    /**     * SoftValue     */    private static class SoftValue extends SoftReference {       private final Object key;       private SoftValue(Object k, Object key, ReferenceQueue q) {          super(k, q);          this.key = key;       }    } }