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

xdean.jex.util.cache.CacheUtil Maven / Gradle / Ivy

The newest version!
package xdean.jex.util.cache;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import com.google.common.collect.MapMaker;

@SuppressWarnings("unchecked")
public class CacheUtil {

  private static final Map, Map>> CACHE_MAP = createMap();

  public static  V cacheWeak(Object key, Supplier factory) {
    return cacheWeak(key.getClass(), key, factory);
  }

  public static  V cacheWeak(Object owner, Object key, Supplier factory) {
    WeakReference ref = cache(owner, key, () -> new WeakReference<>(factory.get()));
    V v = ref.get();
    if (v == null) {
      v = factory.get();
      set(owner, key, new WeakReference<>(v));
    }
    return v;
  }

  public static  V cache(Object key, Supplier factory) {
    return cache(key.getClass(), key, factory);
  }

  public static  V cache(Object owner, Object key, Supplier factory) {
    Map map = getMap(owner);
    if (map.containsKey(key)) {
      return (V) map.get(key);
    }
    V v = factory.get();
    map.put(key, v);
    return v;
  }

  public static  Optional get(Object key) {
    return get(key.getClass(), key);
  }

  public static  Optional get(Object owner, Object key) {
    Map map = getMap(owner);
    if (map.containsKey(key)) {
      return Optional.of((V) map.get(key));
    }
    return Optional.empty();
  }

  public static  void set(Object key, V value) {
    set(key.getClass(), key, value);
  }

  public static  void set(Object owner, Object key, V value) {
    Map map = getMap(owner);
    map.put(key, value);
  }

  public static  Optional remove(Object key) {
    return remove(key.getClass(), key);
  }

  public static  Optional remove(Object owner, Object key) {
    Map map = getMap(owner);
    if (map.containsKey(key)) {
      return Optional.of((V) map.remove(key));
    }
    return Optional.empty();
  }

  private static Map getMap(Object owner) {
    return CACHE_MAP.computeIfAbsent(owner.getClass(), k -> createMap()).computeIfAbsent(owner, k1 -> createMap());
  }

  private static  Map createMap() {
    return new MapMaker().weakKeys().makeMap();// XXX:Synchronize?
  }

  public Map, Map>> getAllCache() {
    return Collections.unmodifiableMap(CACHE_MAP);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy