package tc.oc.commons.core.util; import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import com.google.common.base.Throwables; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public interface CacheUtils { static CacheBuilder newBuilder() { return (CacheBuilder) CacheBuilder.newBuilder(); } static LoadingCache newCache(CacheBuilder builder, ThrowingFunction loader) { return builder.build(new CacheLoader() { @Override public V load(K key) throws E { return loader.applyThrows(key); } }); } static LoadingCache newCache(ThrowingFunction loader) { return newCache(newBuilder(), loader); } static Cache newCache() { return newBuilder().build(); } static LoadingCache newWeakKeyCache(ThrowingFunction loader) { return newCache((CacheBuilder) newBuilder().weakKeys(), loader); } static V getUnchecked(Cache cache, K key, Supplier supplier) { try { return cache.get(key, supplier::get); } catch(ExecutionException e) { throw Throwables.propagate(e); } } }