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

fr.vergne.pester.util.cache.Cache Maven / Gradle / Ivy

The newest version!
package fr.vergne.pester.util.cache;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

public interface Cache {

	 T get(Key key);

	 T get(Key key, Supplier supplier);

	public static Cache create() {
		Map, Object> map = new HashMap<>();
		return new Cache() {
			
			@Override
			public  T get(Key key) {
				return get(key, () -> {throw new IllegalStateException("No value stored for " + key);});
			}
			
			@Override
			public  T get(Key key, Supplier supplier) {
				return key.cast(map.computeIfAbsent(key, k -> supplier.get()));
			}
		};
	}

	public static  Function onFunction(Function function) {
		Cache cache = create();
		return value -> cache.get(ParameteredKey.create(value), () -> function.apply(value));
	}

	public static  Supplier onSupplier(Supplier supplier) {
		Cache cache = create();
		Key key = ParameteredKey.create(new Object());
		return () -> cache.get(key, supplier);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy