Пример #1
0
  @CheckForNull
  public synchronized byte[] get(@Nonnull String obj, @Nullable Callable<byte[]> valueLoader)
      throws Exception {
    String key = getKey(obj);

    try {
      lock();
      if (!forceUpdate) {
        byte[] cached = getCache(key);

        if (cached != null) {
          log.debug("cache hit for " + obj + " -> " + key);
          return cached;
        }

        log.debug("cache miss for " + obj + " -> " + key);
      } else {
        log.debug("cache force update for " + obj + " -> " + key);
      }

      if (valueLoader != null) {
        byte[] value = valueLoader.call();
        if (value != null) {
          putCache(key, value);
        }
        return value;
      }
    } finally {
      unlock();
    }

    return null;
  }
Пример #2
0
  public PersistentCache(
      Path baseDir, long defaultDurationToExpireMs, Log log, boolean forceUpdate) {
    this.baseDir = baseDir;
    this.defaultDurationToExpireMs = defaultDurationToExpireMs;
    this.log = log;

    reconfigure(forceUpdate);
    log.debug("cache: " + baseDir + ", default expiration time (ms): " + defaultDurationToExpireMs);
  }
Пример #3
0
  public void reconfigure(boolean forceUpdate) {
    this.forceUpdate = forceUpdate;

    if (forceUpdate) {
      log.debug("cache: forcing update");
    }

    try {
      Files.createDirectories(baseDir);
    } catch (IOException e) {
      throw new IllegalStateException("failed to create cache dir", e);
    }
  }
Пример #4
0
  private boolean validateCacheEntry(Path cacheEntryPath, long durationToExpireMs)
      throws IOException {
    if (!Files.exists(cacheEntryPath)) {
      return false;
    }

    if (isCacheEntryExpired(cacheEntryPath, durationToExpireMs)) {
      log.debug("cache: expiring entry");
      Files.delete(cacheEntryPath);
      return false;
    }

    return true;
  }