Skip to content
Snippets Groups Projects
Commit 13015300 authored by log2's avatar log2
Browse files

Added cache with three generic parameters: key type, value type and

thrown exceptions (if any)
parent 68a17e4b
No related branches found
No related tags found
No related merge requests found
package com.amd.aparapi.internal.model;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
//import java.util.function.Supplier;
public final class ValueCache<K, V, T extends Throwable> {
// @FunctionalInterface
public interface ThrowingValueComputer<K, V, T extends Throwable> {
V compute(K key) throws T;
}
// @FunctionalInterface
public interface ValueComputer<K, V> extends ThrowingValueComputer<K, V, RuntimeException>{
// Marker interface
}
public static <K, V, T extends Throwable> ValueCache<K, V, T> on(ThrowingValueComputer<K, V, T> computer) {
return new ValueCache<K, V, T>(computer);
}
private final ConcurrentMap<K, SoftReference<V>> map = new ConcurrentHashMap<>();
private final ThrowingValueComputer<K, V, T> computer;
private ValueCache(ThrowingValueComputer<K, V, T> computer) {
this.computer = computer;
}
public V computeIfAbsent(K key) throws T {
Reference<V> reference = map.get(key);
V value = reference == null ? null : reference.get();
if (value == null) {
value = computer.compute(key);
map.put(key, new SoftReference<>(value));
}
return value;
}
public void invalidate() {
map.clear();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment