Java Code Examples for com.github.benmanes.caffeine.cache.Ticker

The following examples show how to use com.github.benmanes.caffeine.cache.Ticker. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: caffeine   Source File: CacheProxy.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"PMD.ExcessiveParameterList", "NullAway"})
public CacheProxy(String name, Executor executor, CacheManager cacheManager,
    CaffeineConfiguration<K, V> configuration,
    com.github.benmanes.caffeine.cache.Cache<K, Expirable<V>> cache,
    EventDispatcher<K, V> dispatcher, Optional<CacheLoader<K, V>> cacheLoader,
    ExpiryPolicy expiry, Ticker ticker, JCacheStatisticsMXBean statistics) {
  this.configuration = requireNonNull(configuration);
  this.cacheManager = requireNonNull(cacheManager);
  this.cacheLoader = requireNonNull(cacheLoader);
  this.dispatcher = requireNonNull(dispatcher);
  this.statistics = requireNonNull(statistics);
  this.executor = requireNonNull(executor);
  this.expiry = requireNonNull(expiry);
  this.ticker = requireNonNull(ticker);
  this.cache = requireNonNull(cache);
  this.name = requireNonNull(name);

  copier = configuration.isStoreByValue()
      ? configuration.getCopierFactory().create()
      : Copier.identity();
  writer = configuration.hasCacheWriter()
      ? configuration.getCacheWriter()
      : DisabledCacheWriter.get();
  cacheMXBean = new JCacheMXBean(this);
}
 
Example 2
/**
  * The cache manager Bean, that defines caching parameters
  *
  * @param ticker The Ticker handle that Spring passes, unused so far
  * @return the cache manager
  */
 @Bean
 public CacheManager cacheManager(Ticker ticker) {
     SimpleCacheManager manager = new SimpleCacheManager();
     if (specs != null) {
         //@formatter:off
List<CaffeineCache> caches =
		specs.entrySet().stream()
			.map(entry -> buildCache(entry.getKey(), entry.getValue(), ticker))
			.collect(Collectors.toList());
//@formatter:on
         manager.setCaches(caches);
     }
     return manager;
 }
 
Example 3
private CaffeineCache buildCache(String name, CacheSpec cacheSpec, Ticker ticker) {
      log.info("Cache {} specified timeout of {} min, max of {}", name, cacheSpec.getTimeout(), cacheSpec.getMax());
      //@formatter:off
final Caffeine<Object, Object> caffeineBuilder
		= Caffeine.newBuilder()
			.expireAfterWrite(cacheSpec.getTimeout(), TimeUnit.MINUTES)
			.maximumSize(cacheSpec.getMax())
			.ticker(ticker);
//@formatter:on
      return new CaffeineCache(name, caffeineBuilder.build());
  }
 
Example 4
@Bean
/**
 * The ticker bean, in case you have to do something time based in the cache manager
 *
 * @return the ticker bean
 */
public Ticker ticker() {
    return Ticker.systemTicker();
}
 
Example 5
Source Project: openapi-generator   Source File: OnceLogger.java    License: Apache License 2.0 5 votes vote down vote up
static void caffeineCache(Ticker ticker, int expireMillis) {
    // Initializes a cache which holds an atomic counter of log message instances.
    // The intent is to debounce log messages such that they occur at most [maxRepetitions] per [expireMillis].
    messageCountCache = Caffeine.newBuilder()
            .maximumSize(maxCacheSize)
            .expireAfterWrite(expireMillis, TimeUnit.MILLISECONDS)
            .ticker(ticker)
            .build();
}
 
Example 6
private Cache<CacheKey, OAuth2TokenResponse> createResponseCache(Ticker cacheTicker, boolean sameThreadCache) {
	Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
			.maximumSize(getCacheConfiguration().getCacheSize())
			.ticker(cacheTicker)
			.expireAfterWrite(getCacheConfiguration().getCacheDuration());
	if (sameThreadCache) {
		cacheBuilder.executor(Runnable::run);
	}
	return cacheBuilder.build();
}
 
Example 7
Source Project: metron   Source File: DefaultMessageDistributor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new message distributor.
 *
 * @param periodDurationMillis The period duration in milliseconds.
 * @param profileTimeToLiveMillis The time-to-live of a profile in milliseconds.
 * @param maxNumberOfRoutes The max number of unique routes to maintain.  After this is exceeded, lesser
 *                          used routes will be evicted from the internal cache.
 * @param ticker The ticker used to drive time for the caches.  Only needs set for testing.
 */
public DefaultMessageDistributor(
        long periodDurationMillis,
        long profileTimeToLiveMillis,
        long maxNumberOfRoutes,
        Ticker ticker) {

  if(profileTimeToLiveMillis < periodDurationMillis) {
    throw new IllegalStateException(format(
            "invalid configuration: expect profile TTL (%d) to be greater than period duration (%d)",
            profileTimeToLiveMillis,
            periodDurationMillis));
  }
  this.periodDurationMillis = periodDurationMillis;

  // build the cache of active profiles
  Caffeine<Integer, ProfileBuilder> activeCacheBuilder = Caffeine
          .newBuilder()
          .maximumSize(maxNumberOfRoutes)
          .expireAfterAccess(profileTimeToLiveMillis, TimeUnit.MILLISECONDS)
          .ticker(ticker)
          .writer(new ActiveCacheWriter());
  if (LOG.isDebugEnabled()) {
    activeCacheBuilder.recordStats();
  }
  this.activeCache = activeCacheBuilder.build();

  // build the cache of expired profiles
  Caffeine<Integer, ProfileBuilder> expiredCacheBuilder = Caffeine
          .newBuilder()
          .maximumSize(maxNumberOfRoutes)
          .expireAfterWrite(profileTimeToLiveMillis, TimeUnit.MILLISECONDS)
          .ticker(ticker)
          .writer(new ExpiredCacheWriter());
  if (LOG.isDebugEnabled()) {
    expiredCacheBuilder.recordStats();
  }
  this.expiredCache = expiredCacheBuilder.build();
}
 
Example 8
Source Project: metron   Source File: DefaultMessageDistributorTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() throws Exception {

  context = Context.EMPTY_CONTEXT();
  JSONParser parser = new JSONParser();
  messageOne = (JSONObject) parser.parse(inputOne);
  messageTwo = (JSONObject) parser.parse(inputTwo);

  distributor = new DefaultMessageDistributor(
          periodDurationMillis,
          profileTimeToLiveMillis,
          maxNumberOfRoutes,
          Ticker.systemTicker());
}
 
Example 9
Source Project: caffeine   Source File: CacheBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testTicker_setTwice() {
  Ticker testTicker = Ticker.systemTicker();
  Caffeine<Object, Object> builder =
      Caffeine.newBuilder().ticker(testTicker);
  try {
    // even to the same instance is not allowed
    builder.ticker(testTicker);
    fail();
  } catch (IllegalStateException expected) {}
}
 
Example 10
Source Project: caffeine   Source File: JCacheLoaderAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("NullAway.Init")
public JCacheLoaderAdapter(CacheLoader<K, V> delegate, EventDispatcher<K, V> dispatcher,
    ExpiryPolicy expiry, Ticker ticker, JCacheStatisticsMXBean statistics) {
  this.dispatcher = requireNonNull(dispatcher);
  this.statistics = requireNonNull(statistics);
  this.delegate = requireNonNull(delegate);
  this.expiry = requireNonNull(expiry);
  this.ticker = requireNonNull(ticker);
}
 
Example 11
Source Project: caffeine   Source File: LoadingCacheProxy.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.ExcessiveParameterList")
public LoadingCacheProxy(String name, Executor executor, CacheManager cacheManager,
    CaffeineConfiguration<K, V> configuration, LoadingCache<K, Expirable<V>> cache,
    EventDispatcher<K, V> dispatcher, CacheLoader<K, V> cacheLoader,
    ExpiryPolicy expiry, Ticker ticker, JCacheStatisticsMXBean statistics) {
  super(name, executor, cacheManager, configuration, cache, dispatcher,
      Optional.of(cacheLoader), expiry, ticker, statistics);
  this.cache = cache;
}
 
Example 12
public AbstractOAuth2TokenService() {
	this(TokenCacheConfiguration.defaultConfiguration(), Ticker.systemTicker(), false);
}
 
Example 13
Source Project: Groza   Source File: CaffeineCacheConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public Ticker ticker() {
    return Ticker.systemTicker();
}
 
Example 14
Source Project: metron   Source File: DefaultMessageDistributorTest.java    License: Apache License 2.0 4 votes vote down vote up
public FixedTicker() {
  this.timestampNanos = Ticker.systemTicker().read();
}
 
Example 15
/**
 * This constructor is used for testing purposes only.
 *
 * @param tokenCacheConfiguration
 *            sets the cache configuration used to configure or disable the
 *            cache.
 * @param cacheTicker
 *            will be used in the cache to determine the time.
 * @param sameThreadCache
 *            set to true disables maintenance jobs of the cache. This makes the
 *            cache slower but more predictable for testing.
 */
AbstractOAuth2TokenService(TokenCacheConfiguration tokenCacheConfiguration, Ticker cacheTicker,
		boolean sameThreadCache) {
	Assertions.assertNotNull(tokenCacheConfiguration, "cacheConfiguration is required");
	this.tokenCacheConfiguration = tokenCacheConfiguration;
	this.responseCache = createResponseCache(cacheTicker, sameThreadCache);
	if (isCacheDisabled()) {
		LOGGER.debug("Configured token service with cache disabled");
	} else {
		LOGGER.debug("Configured token service with {}", tokenCacheConfiguration);
	}
}
 
Example 16
Source Project: metron   Source File: DefaultMessageDistributor.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Create a new message distributor.
 *
 * @param periodDurationMillis The period duration in milliseconds.
 * @param profileTimeToLiveMillis The time-to-live of a profile in milliseconds.
 * @param maxNumberOfRoutes The max number of unique routes to maintain.  After this is exceeded, lesser
 *                          used routes will be evicted from the internal cache.
 */
public DefaultMessageDistributor(
        long periodDurationMillis,
        long profileTimeToLiveMillis,
        long maxNumberOfRoutes) {
  this(periodDurationMillis, profileTimeToLiveMillis, maxNumberOfRoutes, Ticker.systemTicker());
}
 
Example 17
/**
 * Constructor used to overwrite the default cache configuration.
 *
 * @param tokenCacheConfiguration
 *            the cache configuration used to configure the cache.
 */
public AbstractOAuth2TokenService(TokenCacheConfiguration tokenCacheConfiguration) {
	this(tokenCacheConfiguration, Ticker.systemTicker(), false);

}
 
Example 18
Source Project: caffeine   Source File: CaffeineConfiguration.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Returns the {@link Factory} for the {@link Ticker} to be used for the cache.
 *
 * @return the {@link Factory} for the {@link Ticker}
 */
public Factory<Ticker> getTickerFactory() {
  return tickerFactory;
}
 
Example 19
Source Project: caffeine   Source File: CaffeineConfiguration.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Set the {@link Factory} for the {@link Ticker}.
 *
 * @param factory the {@link Ticker} {@link Factory}
 */
public void setTickerFactory(Factory<Ticker> factory) {
  tickerFactory = requireNonNull(factory);
}