com.github.benmanes.caffeine.cache.Caffeine.requireState()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(15.9k)|赞(0)|评价(0)|浏览(168)

本文整理了Java中com.github.benmanes.caffeine.cache.Caffeine.requireState()方法的一些代码示例,展示了Caffeine.requireState()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Caffeine.requireState()方法的具体详情如下:
包路径:com.github.benmanes.caffeine.cache.Caffeine
类名称:Caffeine
方法名:requireState

Caffeine.requireState介绍

[英]Ensures that the state expression is true.
[中]确保状态表达式为true。

代码示例

代码示例来源:origin: ben-manes/caffeine

void requireNonLoadingCache() {
 requireState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
}

代码示例来源:origin: ben-manes/caffeine

void requireWeightWithWeigher() {
 if (weigher == null) {
  requireState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
 } else if (strictParsing) {
  requireState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
 } else if (maximumWeight == UNSET_INT) {
  logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
 }
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that each key (not value) stored in the cache should be wrapped in a
 * {@link WeakReference} (by default, strong references are used).
 * <p>
 * <b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
 * comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore
 * technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap}
 * does).
 * <p>
 * Entries with keys that have been garbage collected may be counted in
 * {@link Cache#estimatedSize()}, but will never be visible to read or write operations; such
 * entries are cleaned up as part of the routine maintenance described in the class javadoc.
 * <p>
 * This feature cannot be used in conjunction with {@link #writer}.
 *
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalStateException if the key strength was already set or the writer was set
 */
@NonNull
public Caffeine<K, V> weakKeys() {
 requireState(keyStrength == null, "Key strength was already set to %s", keyStrength);
 requireState(writer == null, "Weak keys may not be used with CacheWriter");
 keyStrength = Strength.WEAK;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Enables the accumulation of {@link CacheStats} during the operation of the cache. Without this
 * {@link Cache#stats} will return zero for all statistics. Note that recording statistics
 * requires bookkeeping to be performed with each operation, and thus imposes a performance
 * penalty on cache operation.
 *
 * @return this {@code Caffeine} instance (for chaining)
 */
@NonNull
public Caffeine<K, V> recordStats() {
 requireState(this.statsCounterSupplier == null, "Statistics recording was already set");
 statsCounterSupplier = ENABLED_STATS_COUNTER_SUPPLIER;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

@NonNull Expiry<? super K1, ? super V1> expiry) {
requireNonNull(expiry);
requireState(this.expiry == null, "Expiry was already set to %s", this.expiry);
requireState(this.expireAfterAccessNanos == UNSET_INT,
  "Expiry may not be used with expiresAfterAccess");
requireState(this.expireAfterWriteNanos == UNSET_INT,
  "Expiry may not be used with expiresAfterWrite");

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that each value (not key) stored in the cache should be wrapped in a
 * {@link WeakReference} (by default, strong references are used).
 * <p>
 * Weak values will be garbage collected once they are weakly reachable. This makes them a poor
 * candidate for caching; consider {@link #softValues} instead.
 * <p>
 * <b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
 * comparison to determine equality of values.
 * <p>
 * Entries with values that have been garbage collected may be counted in
 * {@link Cache#estimatedSize()}, but will never be visible to read or write operations; such
 * entries are cleaned up as part of the routine maintenance described in the class javadoc.
 * <p>
 * This feature cannot be used in conjunction with {@link #buildAsync}.
 *
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalStateException if the value strength was already set
 */
@NonNull
public Caffeine<K, V> weakValues() {
 requireState(valueStrength == null, "Value strength was already set to %s", valueStrength);
 valueStrength = Strength.WEAK;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies the maximum number of entries the cache may contain. Note that the cache <b>may evict
 * an entry before this limit is exceeded or temporarily exceed the threshold while evicting</b>.
 * As the cache size grows close to the maximum, the cache evicts entries that are less likely to
 * be used again. For example, the cache may evict an entry because it hasn't been used recently
 * or very often.
 * <p>
 * When {@code size} is zero, elements will be evicted immediately after being loaded into the
 * cache. This can be useful in testing, or to disable caching temporarily without a code change.
 * <p>
 * This feature cannot be used in conjunction with {@link #maximumWeight}.
 *
 * @param maximumSize the maximum size of the cache
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalArgumentException if {@code size} is negative
 * @throws IllegalStateException if a maximum size or weight was already set
 */
@NonNull
public Caffeine<K, V> maximumSize(@NonNegative long maximumSize) {
 requireState(this.maximumSize == UNSET_INT,
   "maximum size was already set to %s", this.maximumSize);
 requireState(this.maximumWeight == UNSET_INT,
   "maximum weight was already set to %s", this.maximumWeight);
 requireState(this.weigher == null, "maximum size can not be combined with weigher");
 requireArgument(maximumSize >= 0, "maximum size must not be negative");
 this.maximumSize = maximumSize;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that each value (not key) stored in the cache should be wrapped in a
 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
 * demand.
 * <p>
 * <b>Warning:</b> in most circumstances it is better to set a per-cache
 * {@linkplain #maximumSize(long) maximum size} instead of using soft references. You should only
 * use this method if you are very familiar with the practical consequences of soft references.
 * <p>
 * <b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
 * comparison to determine equality of values.
 * <p>
 * Entries with values that have been garbage collected may be counted in
 * {@link Cache#estimatedSize()}, but will never be visible to read or write operations; such
 * entries are cleaned up as part of the routine maintenance described in the class javadoc.
 * <p>
 * This feature cannot be used in conjunction with {@link #buildAsync}.
 *
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalStateException if the value strength was already set
 */
@NonNull
public Caffeine<K, V> softValues() {
 requireState(valueStrength == null, "Value strength was already set to %s", valueStrength);
 valueStrength = Strength.SOFT;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies a nanosecond-precision time source for use in determining when entries should be
 * expired or refreshed. By default, {@link System#nanoTime} is used.
 * <p>
 * The primary intent of this method is to facilitate testing of caches which have been configured
 * with {@link #expireAfterWrite}, {@link #expireAfterAccess}, or {@link #refreshAfterWrite}.
 *
 * @param ticker a nanosecond-precision time source
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalStateException if a ticker was already set
 * @throws NullPointerException if the specified ticker is null
 */
@NonNull
public Caffeine<K, V> ticker(@NonNull Ticker ticker) {
 requireState(this.ticker == null, "Ticker was already set to %s", this.ticker);
 this.ticker = requireNonNull(ticker);
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies the executor to use when running asynchronous tasks. The executor is delegated to
 * when sending removal notifications, when asynchronous computations are performed by
 * {@link AsyncLoadingCache} or {@link LoadingCache#refresh} or {@link #refreshAfterWrite}, or
 * when performing periodic maintenance. By default, {@link ForkJoinPool#commonPool()} is used.
 * <p>
 * The primary intent of this method is to facilitate testing of caches which have been
 * configured with {@link #removalListener} or utilize asynchronous computations. A test may
 * instead prefer to configure the cache to execute tasks directly on the same thread.
 * <p>
 * Beware that configuring a cache with an executor that throws {@link RejectedExecutionException}
 * may experience non-deterministic behavior.
 *
 * @param executor the executor to use for asynchronous execution
 * @return this {@code Caffeine} instance (for chaining)
 * @throws NullPointerException if the specified executor is null
 */
@NonNull
public Caffeine<K, V> executor(@NonNull Executor executor) {
 requireState(this.executor == null, "executor was already set to %s", this.executor);
 this.executor = requireNonNull(executor);
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Enables the accumulation of {@link CacheStats} during the operation of the cache. Without this
 * {@link Cache#stats} will return zero for all statistics. Note that recording statistics
 * requires bookkeeping to be performed with each operation, and thus imposes a performance
 * penalty on cache operation. Any exception thrown by the supplied {@link StatsCounter} will be
 * suppressed and logged.
 *
 * @param statsCounterSupplier a supplier instance that returns a new {@link StatsCounter}
 * @return this {@code Caffeine} instance (for chaining)
 */
@NonNull
public Caffeine<K, V> recordStats(
  @NonNull Supplier<? extends StatsCounter> statsCounterSupplier) {
 requireState(this.statsCounterSupplier == null, "Statistics recording was already set");
 requireNonNull(statsCounterSupplier);
 this.statsCounterSupplier = () -> StatsCounter.guardedStatsCounter(statsCounterSupplier.get());
 return this;
}

代码示例来源:origin: ben-manes/caffeine

requireState(this.maximumWeight == UNSET_INT,
  "maximum weight was already set to %s", this.maximumWeight);
requireState(this.maximumSize == UNSET_INT,
  "maximum size was already set to %s", this.maximumSize);
this.maximumWeight = maximumWeight;

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry's creation, or the most recent replacement of its value.
 * <p>
 * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to
 * read or write operations. Expired entries are cleaned up as part of the routine maintenance
 * described in the class javadoc.
 * <p>
 * If you can represent the duration as a {@link java.time.Duration} (which should be preferred
 * when feasible), use {@link #expireAfterWrite(Duration)} instead.
 *
 * @param duration the length of time after an entry is created that it should be automatically
 *        removed
 * @param unit the unit that {@code duration} is expressed in
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalArgumentException if {@code duration} is negative
 * @throws IllegalStateException if the time to live or variable expiration was already set
 */
@NonNull
public Caffeine<K, V> expireAfterWrite(@NonNegative long duration, @NonNull TimeUnit unit) {
 requireState(expireAfterWriteNanos == UNSET_INT,
   "expireAfterWrite was already set to %s ns", expireAfterWriteNanos);
 requireState(expiry == null, "expireAfterWrite may not be used with variable expiration");
 requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
 this.expireAfterWriteNanos = unit.toNanos(duration);
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry's creation, the most recent replacement of its value, or its last
 * read. Access time is reset by all cache read and write operations (including
 * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
 * on the collection-views of {@link Cache#asMap}.
 * <p>
 * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to
 * read or write operations. Expired entries are cleaned up as part of the routine maintenance
 * described in the class javadoc.
 * <p>
 * If you can represent the duration as a {@link java.time.Duration} (which should be preferred
 * when feasible), use {@link #expireAfterAccess(Duration)} instead.
 *
 * @param duration the length of time after an entry is last accessed that it should be
 *        automatically removed
 * @param unit the unit that {@code duration} is expressed in
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalArgumentException if {@code duration} is negative
 * @throws IllegalStateException if the time to idle or variable expiration was already set
 */
@NonNull
public Caffeine<K, V> expireAfterAccess(@NonNegative long duration, @NonNull TimeUnit unit) {
 requireState(expireAfterAccessNanos == UNSET_INT,
   "expireAfterAccess was already set to %s ns", expireAfterAccessNanos);
 requireState(expiry == null, "expireAfterAccess may not be used with variable expiration");
 requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
 this.expireAfterAccessNanos = unit.toNanos(duration);
 return this;
}

代码示例来源:origin: ben-manes/caffeine

public <K1 extends K, V1 extends V> Caffeine<K1, V1> removalListener(
  @NonNull RemovalListener<? super K1, ? super V1> removalListener) {
 requireState(this.removalListener == null,
   "removal listener was already set to %s", this.removalListener);

代码示例来源:origin: ben-manes/caffeine

@Override
public void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause) {
 requireState(hasRemovalListener(), "Notification should be guarded with a check");
 Runnable task = () -> {
  try {
   removalListener().onRemoval(key, value, cause);
  } catch (Throwable t) {
   logger.log(Level.WARNING, "Exception thrown by removal listener", t);
  }
 };
 try {
  executor().execute(task);
 } catch (Throwable t) {
  logger.log(Level.SEVERE, "Exception thrown when submitting removal listener", t);
  task.run();
 }
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Sets the minimum total size for the internal data structures. Providing a large enough estimate
 * at construction time avoids the need for expensive resizing operations later, but setting this
 * value unnecessarily high wastes memory.
 *
 * @param initialCapacity minimum total size for the internal data structures
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalArgumentException if {@code initialCapacity} is negative
 * @throws IllegalStateException if an initial capacity was already set
 */
@NonNull
public Caffeine<K, V> initialCapacity(@NonNegative int initialCapacity) {
 requireState(this.initialCapacity == UNSET_INT,
   "initial capacity was already set to %s", this.initialCapacity);
 requireArgument(initialCapacity >= 0);
 this.initialCapacity = initialCapacity;
 return this;
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Specifies that active entries are eligible for automatic refresh once a fixed duration has
 * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
 * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling
 * {@link CacheLoader#reload}.
 * <p>
 * Automatic refreshes are performed when the first stale request for an entry occurs. The request
 * triggering refresh will make an asynchronous call to {@link CacheLoader#reload} and immediately
 * return the old value.
 * <p>
 * <b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
 * <p>
 * If you can represent the duration as a {@link java.time.Duration} (which should be preferred
 * when feasible), use {@link #refreshAfterWrite(Duration)} instead.
 *
 * @param duration the length of time after an entry is created that it should be considered
 *        stale, and thus eligible for refresh
 * @param unit the unit that {@code duration} is expressed in
 * @return this {@code Caffeine} instance (for chaining)
 * @throws IllegalArgumentException if {@code duration} is zero or negative
 * @throws IllegalStateException if the refresh interval was already set
 */
@NonNull
public Caffeine<K, V> refreshAfterWrite(@NonNegative long duration, @NonNull TimeUnit unit) {
 requireNonNull(unit);
 requireState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
 requireArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
 this.refreshNanos = unit.toNanos(duration);
 return this;
}

代码示例来源:origin: ben-manes/caffeine

requireState(valueStrength == null, "Weak or soft values can not be combined with AsyncCache");
requireState(writer == null, "CacheWriter can not be combined with AsyncCache");
requireWeightWithWeigher();
requireNonLoadingCache();

代码示例来源:origin: ben-manes/caffeine

public <K1 extends K, V1 extends V> AsyncLoadingCache<K1, V1> buildAsync(
  @NonNull AsyncCacheLoader<? super K1, V1> loader) {
 requireState(valueStrength == null,
   "Weak or soft values can not be combined with AsyncLoadingCache");
 requireState(writer == null, "CacheWriter can not be combined with AsyncLoadingCache");
 requireWeightWithWeigher();
 requireNonNull(loader);

相关文章