All Downloads are FREE. Search and download functionalities are using the official Maven repository.

convex.core.util.SoftCache Maven / Gradle / Ivy

The newest version!
package convex.core.util;

import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Set;
import java.util.WeakHashMap;

/**
 * Cache with weak keys and soft referenced values
 */
public class SoftCache extends AbstractMap {
	private WeakHashMap> cache=new WeakHashMap>();
	
	public V get(Object key) {
		SoftReference sr=getSoftReference(key);
		if (sr==null) return null;
		return sr.get();
	}

	public SoftReference getSoftReference(Object key) {
		return cache.get(key);
	}
	
	@Override
	public V put(K key, V value) {
		SoftReference sr=new SoftReference<>(value);
		cache.put(key, sr);
		return null;
	}
	
	public SoftReference putReference(K key, SoftReference valueRef) {
		return cache.put(key, valueRef);
	}

	@Override
	public Set> entrySet() {
		HashSet> result=new HashSet>();
		
		for (Entry> e: cache.entrySet()) {
			V val=e.getValue().get();
			if (val!=null) {
				result.add(new AbstractMap.SimpleEntry<>(e.getKey(),val));
			}
		}
		return result;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy