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

io.setl.json.primitive.cache.SimpleLruCache Maven / Gradle / Ivy

Go to download

An implementation of the Canonical JSON format with support for javax.json and Jackson

The newest version!
package io.setl.json.primitive.cache;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import javax.annotation.Nonnull;

/**
 * A very simple LRU cache based on LinkedHashMap. The cache can only be accessed by one thread at a time.
 *
 * @author Simon Greatrix on 05/02/2020.
 */
public class SimpleLruCache implements ICache {

  private static class Cache extends LinkedHashMap {

    private final int maxSize;


    public Cache(int maxSize) {
      this.maxSize = maxSize;
    }


    @Override
    protected boolean removeEldestEntry(Entry eldest) {
      return size() > maxSize;
    }

  }



  private final Map myCache;


  /**
   * New instance.
   *
   * @param maxSize number of items to hold in the cache
   */
  public SimpleLruCache(int maxSize) {
    myCache = new Cache<>(maxSize);
  }


  @Nonnull
  @Override
  public V get(K key, Function creator) {
    synchronized (myCache) {
      return myCache.computeIfAbsent(key, creator);
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy