diff src/fschmidt/util/java/TimedCacheMap.java @ 68:00520880ad02

add fschmidt source
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 05 Oct 2025 17:24:15 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/fschmidt/util/java/TimedCacheMap.java	Sun Oct 05 17:24:15 2025 -0600
@@ -0,0 +1,87 @@
+/*
+Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+package fschmidt.util.java;
+
+import java.util.Map;
+import java.util.LinkedHashMap;
+import java.util.Iterator;
+import fschmidt.db.util.WeakCacheMap;
+
+
+public class TimedCacheMap<K,V> extends WeakCacheMap<K,V> {
+
+	private static class IdentityRef {
+		private final Object obj;
+
+		IdentityRef(Object obj) {
+			this.obj = obj;
+		}
+
+		public int hashCode() {
+			return System.identityHashCode(obj);
+		}
+
+		public boolean equals(Object obj) {
+			return obj instanceof IdentityRef
+				&& obj==((IdentityRef)obj).obj;
+		}
+	}
+
+	private final long timeLimit;
+	private final Map<IdentityRef,Long> vals = new LinkedHashMap<IdentityRef,Long>();
+
+	public TimedCacheMap(long timeLimit) {
+		this.timeLimit = timeLimit;
+	}
+
+	private void add(V value,long now) {
+		if( value==null )
+			return;
+		IdentityRef ref = new IdentityRef(value);
+		vals.remove(ref);
+		vals.put( ref, now + timeLimit );
+	}
+
+	private void sweep(long now) {
+		for( Iterator<Long> i = vals.values().iterator(); i.hasNext(); ) {
+			long time = i.next();
+			if( time > now )
+				return;
+			i.remove();
+		}
+	}
+
+	public V put(K key, V value) {
+		long now = System.currentTimeMillis();
+		sweep(now);
+		add(value,now);
+		return super.put(key,value);
+	}
+
+	public V get(Object key) {
+		long now = System.currentTimeMillis();
+		V value = super.get(key);
+		add(value,now);
+		return value;
+	}
+}