package mage.client.util; import static com.google.common.cache.CacheBuilder.newBuilder; import java.util.Optional; import java.util.concurrent.ExecutionException; import com.google.common.base.Function; import com.google.common.cache.CacheLoader; import com.google.common.cache.ForwardingLoadingCache; import com.google.common.cache.LoadingCache; import org.apache.log4j.Logger; public class SoftValuesLoadingCache extends ForwardingLoadingCache> { private final LoadingCache> cache; private static final Logger logger = Logger.getLogger(SoftValuesLoadingCache.class); public SoftValuesLoadingCache(CacheLoader> loader) { cache = newBuilder().softValues().build(loader); } @Override protected LoadingCache> delegate() { return cache; } public V getOrThrow(K key) { V v = getOrNull(key); if (v == null) { throw new NullPointerException(); } return v; } public V getOrNull(K key) { try { return get(key).orElse(null); } catch (ExecutionException e) { if (e.getCause() instanceof OutOfMemoryError) { logger.warn("Out of memory error: try to increase free memory in launcher options (-xmx param)"); return null; } else { throw new RuntimeException(e); } } catch (Throwable e) { return null; } } public V peekIfPresent(K key) { Optional value = getIfPresent(key); if (value != null) { return value.orElse(null); } return null; } public static SoftValuesLoadingCache from(CacheLoader> loader) { return new SoftValuesLoadingCache<>(loader); } public static SoftValuesLoadingCache from(Function loader) { return from(CacheLoader.from(k -> Optional.ofNullable(loader.apply(k)))); } }