001package io.ebean.cache;
002
003import io.ebean.meta.MetricVisitor;
004
005import java.util.LinkedHashMap;
006import java.util.Map;
007import java.util.Set;
008
009/**
010 * Represents part of the "L2" server side cache.
011 * <p>
012 * This is used to cache beans or query results (bean collections).
013 * <p>
014 * There are 2 ServerCache's for each bean type. One is used as the 'bean cache'
015 * which holds beans of a given type. The other is the 'query cache' holding
016 * query results for a given type.
017 */
018public interface ServerCache {
019
020  /**
021   * Get values for many keys.
022   */
023  default Map<Object, Object> getAll(Set<Object> keys) {
024    Map<Object, Object> map = new LinkedHashMap<>();
025    for (Object key : keys) {
026      Object value = get(key);
027      if (value != null) {
028        map.put(key, value);
029      }
030    }
031    return map;
032  }
033
034  /**
035   * Return the value given the key.
036   */
037  Object get(Object id);
038
039  /**
040   * Put all the values in the cache.
041   */
042  default void putAll(Map<Object, Object> keyValues) {
043    keyValues.forEach(this::put);
044  }
045
046  /**
047   * Put the value in the cache with a given id.
048   */
049  void put(Object id, Object value);
050
051  /**
052   * Remove the entries from the cache given the id values.
053   */
054  default void removeAll(Set<Object> keys) {
055    keys.forEach(this::remove);
056  }
057
058  /**
059   * Remove a entry from the cache given its id.
060   */
061  void remove(Object id);
062
063  /**
064   * Clear all entries from the cache.
065   */
066  void clear();
067
068  /**
069   * Return the number of entries in the cache.
070   */
071  int size();
072
073  /**
074   * Return the hit ratio the cache is currently getting.
075   */
076  default int hitRatio() {
077    return getHitRatio();
078  }
079
080  /**
081   * Deprecated migrate to hitRatio().
082   */
083  @Deprecated
084  int getHitRatio();
085
086  /**
087   * Return statistics for the cache.
088   *
089   * @param reset if true the statistics are reset.
090   */
091  default ServerCacheStatistics statistics(boolean reset) {
092    return getStatistics(reset);
093  }
094
095  /**
096   * Deprecated migrate to statistics().
097   */
098  @Deprecated
099  ServerCacheStatistics getStatistics(boolean reset);
100
101  /**
102   * Visit the metrics for the cache.
103   */
104  default void visit(MetricVisitor visitor) {
105    // do nothing by default
106  }
107}