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

com.hubspot.singularity.data.ZkCache Maven / Gradle / Ivy

package com.hubspot.singularity.data;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

public class ZkCache {
  private final Cache cache;
  private final Meter hitMeter;
  private final Meter missMeter;

  public ZkCache(
    int maxSize,
    int initialSize,
    long millisToExpireAfterAccess,
    MetricRegistry registry,
    String name
  ) {
    cache =
      CacheBuilder
        .newBuilder()
        .maximumSize(maxSize)
        .concurrencyLevel(2)
        .initialCapacity(initialSize)
        .expireAfterAccess(millisToExpireAfterAccess, TimeUnit.MILLISECONDS)
        .build();

    this.hitMeter = registry.meter(String.format("zk.caches.%s.hits", name));
    this.missMeter = registry.meter(String.format("zk.caches.%s.miss", name));

    registry.register(
      String.format("zk.caches.%s.size", name),
      new Gauge() {

        @Override
        public Long getValue() {
          return cache.size();
        }
      }
    );
  }

  @SuppressFBWarnings("NP_NULL_PARAM_DEREF")
  public Optional get(String path) {
    T fromCache = cache.getIfPresent(path);

    if (fromCache == null) {
      missMeter.mark();
    } else {
      hitMeter.mark();
    }

    return Optional.ofNullable(fromCache);
  }

  public void delete(String path) {
    cache.invalidate(path);
  }

  public void set(String path, T object) {
    cache.put(path, object);
  }

  public void invalidateAll() {
    cache.invalidateAll();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy