Java Code Examples for com.github.benmanes.caffeine.cache.Caffeine#maximumSize()

The following examples show how to use com.github.benmanes.caffeine.cache.Caffeine#maximumSize() . 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 File: CaffeineCache.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public CaffeineCache(CaffeineCacheInfo cacheInfo, Executor executor) {
    this.name = cacheInfo.name;
    Caffeine<Object, Object> builder = Caffeine.newBuilder();
    if (executor != null) {
        builder.executor(executor);
    }
    if (cacheInfo.initialCapacity != null) {
        this.initialCapacity = cacheInfo.initialCapacity;
        builder.initialCapacity(cacheInfo.initialCapacity);
    }
    if (cacheInfo.maximumSize != null) {
        this.maximumSize = cacheInfo.maximumSize;
        builder.maximumSize(cacheInfo.maximumSize);
    }
    if (cacheInfo.expireAfterWrite != null) {
        this.expireAfterWrite = cacheInfo.expireAfterWrite;
        builder.expireAfterWrite(cacheInfo.expireAfterWrite);
    }
    if (cacheInfo.expireAfterAccess != null) {
        this.expireAfterAccess = cacheInfo.expireAfterAccess;
        builder.expireAfterAccess(cacheInfo.expireAfterAccess);
    }
    cache = builder.buildAsync();
}
 
Example 2
Source File: CaffeineCache.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private Cache<K, V> buildCache(Cache<K, V> prev) {
  @SuppressWarnings({"rawtypes"})
  Caffeine builder = Caffeine.newBuilder()
      .initialCapacity(initialSize)
      .executor(executor)
      .removalListener(this)
      .recordStats();
  if (maxIdleTimeSec > 0) {
    builder.expireAfterAccess(Duration.ofSeconds(maxIdleTimeSec));
  }
  if (maxRamBytes != Long.MAX_VALUE) {
    builder.maximumWeight(maxRamBytes);
    builder.weigher((k, v) -> (int) (RamUsageEstimator.sizeOfObject(k) + RamUsageEstimator.sizeOfObject(v)));
  } else {
    builder.maximumSize(maxSize);
  }
  Cache<K, V> newCache = builder.build();
  if (prev != null) {
    newCache.putAll(prev.asMap());
  }
  return newCache;
}
 
Example 3
Source File: CaffeinePolicy.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public CaffeinePolicy(Config config, Set<Characteristic> characteristics) {
  policyStats = new PolicyStats("product.Caffeine");
  BasicSettings settings = new BasicSettings(config);
  Caffeine<Long, AccessEvent> builder = Caffeine.newBuilder()
      .removalListener((Long key, AccessEvent value, RemovalCause cause) ->
          policyStats.recordEviction())
      .initialCapacity(settings.maximumSize())
      .executor(Runnable::run);
  if (characteristics.contains(WEIGHTED)) {
    builder.maximumWeight(settings.maximumSize());
    builder.weigher((key, value) -> value.weight());
  } else {
    builder.maximumSize(settings.maximumSize());
  }
  cache = builder.build();
}
 
Example 4
Source File: CaffeineCacheFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> build(final String name, final CacheConfig<K, V> config) {
    Caffeine<Object, Object> builder = Caffeine.newBuilder();
    if (config.getExpireAfterWrite() > 0) {
        builder.expireAfterWrite(config.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    builder.maximumSize(config.getCapacity() > 0 ? config.getCapacity() : Long.MAX_VALUE);
    com.github.benmanes.caffeine.cache.Cache<K, CacheObject<V>> cache = builder.build();
    return new CaffeineCache<>(cache, config);
}
 
Example 5
Source File: CacheBuilderFactory.java    From caffeine with Apache License 2.0 5 votes vote down vote up
private Caffeine<Object, Object> createCacheBuilder(
    Integer concurrencyLevel, Integer initialCapacity, Integer maximumSize,
    DurationSpec expireAfterWrite, DurationSpec expireAfterAccess, DurationSpec refresh,
    Strength keyStrength, Strength valueStrength) {

  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  if (concurrencyLevel != null) {
    //builder.concurrencyLevel(concurrencyLevel);
  }
  if (initialCapacity != null) {
    builder.initialCapacity(initialCapacity);
  }
  if (maximumSize != null) {
    builder.maximumSize(maximumSize);
  }
  if (expireAfterWrite != null) {
    builder.expireAfterWrite(expireAfterWrite.duration, expireAfterWrite.unit);
  }
  if (expireAfterAccess != null) {
    builder.expireAfterAccess(expireAfterAccess.duration, expireAfterAccess.unit);
  }
  if (refresh != null) {
    builder.refreshAfterWrite(refresh.duration, refresh.unit);
  }
  if (keyStrength == Strength.WEAK) {
    builder.weakKeys();
  }
  if (valueStrength == Strength.WEAK) {
    builder.weakValues();
  } else if (valueStrength == Strength.SOFT) {
    builder.softValues();
  }
  builder.executor(MoreExecutors.directExecutor());
  return builder;
}
 
Example 6
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testMaximumSize_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.maximumSize(-1);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 7
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testMaximumSize_setTwice() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder().maximumSize(16);
  try {
    // even to the same value is not allowed
    builder.maximumSize(16);
    fail();
  } catch (IllegalStateException expected) {}
}
 
Example 8
Source File: LocalCacheListener.java    From redisson with Apache License 2.0 5 votes vote down vote up
public ConcurrentMap<CacheKey, CacheValue> createCache(LocalCachedMapOptions<?, ?> options) {
    if (options.getCacheProvider() == LocalCachedMapOptions.CacheProvider.CAFFEINE) {
        Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder();
        if (options.getTimeToLiveInMillis() > 0) {
            caffeineBuilder.expireAfterWrite(options.getTimeToLiveInMillis(), TimeUnit.MILLISECONDS);
        }
        if (options.getMaxIdleInMillis() > 0) {
            caffeineBuilder.expireAfterAccess(options.getMaxIdleInMillis(), TimeUnit.MILLISECONDS);
        }
        if (options.getCacheSize() > 0) {
            caffeineBuilder.maximumSize(options.getCacheSize());
        }
        if (options.getEvictionPolicy() == LocalCachedMapOptions.EvictionPolicy.SOFT) {
            caffeineBuilder.softValues();
        }
        if (options.getEvictionPolicy() == LocalCachedMapOptions.EvictionPolicy.WEAK) {
            caffeineBuilder.weakValues();
        }
        return caffeineBuilder.<CacheKey, CacheValue>build().asMap();
    }

    if (options.getEvictionPolicy() == EvictionPolicy.NONE) {
        return new NoneCacheMap<>(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.LRU) {
        return new LRUCacheMap<>(options.getCacheSize(), options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.LFU) {
        return new LFUCacheMap<>(options.getCacheSize(), options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.SOFT) {
        return ReferenceCacheMap.soft(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    if (options.getEvictionPolicy() == EvictionPolicy.WEAK) {
        return ReferenceCacheMap.weak(options.getTimeToLiveInMillis(), options.getMaxIdleInMillis());
    }
    throw new IllegalArgumentException("Invalid eviction policy: " + options.getEvictionPolicy());
}
 
Example 9
Source File: CaffeineCache.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public CaffeineCache(String name, int capacity, Mapper<K, V> loader, long ttl, boolean statistics, boolean manageable) {
	this.name = name;
	this.capacity = capacity;
	this.ttl = ttl;
	this.loading = loader != null;

	Caffeine<Object, Object> builder = Caffeine.newBuilder();

	if (capacity > 0) {
		builder.maximumSize(capacity);
	}

	if (ttl > 0) {
		builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
	}

	if (statistics) {
		builder.recordStats();
	}

	if (manageable) {
		new ManageableCache(this);
	}

	if (loading) {
		this.loadingCache = builder.build(loader::map);
		this.cache = loadingCache;

	} else {
		this.loadingCache = null;
		this.cache = builder.build();
	}
}
 
Example 10
Source File: L2Cache.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new Entity cache
 *
 * @param repository the {@link Repository} to load the entities from
 * @return newly created LoadingCache
 */
private LoadingCache<Object, Optional<Map<String, Object>>> createEntityCache(
    Repository<Entity> repository) {
  Caffeine<Object, Object> cacheBuilder =
      Caffeine.newBuilder().recordStats().expireAfterAccess(10, MINUTES);
  if (!MetaDataService.isMetaEntityType(repository.getEntityType())) {
    cacheBuilder.maximumSize(MAX_CACHE_SIZE_PER_ENTITY);
  }
  LoadingCache<Object, Optional<Map<String, Object>>> cache =
      CaffeinatedGuava.build(cacheBuilder, createCacheLoader(repository));
  GuavaCacheMetrics.monitor(meterRegistry, cache, "l2." + repository.getEntityType().getId());
  return cache;
}
 
Example 11
Source File: CaffeineUtils.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheName
 * @param timeToLiveSeconds 设置写缓存后过期时间(单位:秒)
 * @param timeToIdleSeconds 设置读缓存后过期时间(单位:秒)
 * @param initialCapacity
 * @param maximumSize
 * @param recordStats
 * @param removalListener
 * @return
 */
public static <K, V> LoadingCache<K, V> createLoadingCache(String cacheName, Long timeToLiveSeconds, Long timeToIdleSeconds, Integer initialCapacity, Integer maximumSize,
        boolean recordStats, RemovalListener<K, V> removalListener) {

	if (removalListener == null) {
		removalListener = new DefaultRemovalListener<K, V>(cacheName);
	}

	Caffeine<K, V> cacheBuilder = Caffeine.newBuilder().removalListener(removalListener);

	//设置并发级别为8,并发级别是指可以同时写缓存的线程数
	//		cacheBuilder.concurrencyLevel(concurrencyLevel);
	if (timeToLiveSeconds != null && timeToLiveSeconds > 0) {
		//设置写缓存后8秒钟过期
		cacheBuilder.expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS);
	}
	if (timeToIdleSeconds != null && timeToIdleSeconds > 0) {
		//设置访问缓存后8秒钟过期
		cacheBuilder.expireAfterAccess(timeToIdleSeconds, TimeUnit.SECONDS);
	}

	//设置缓存容器的初始容量为10
	cacheBuilder.initialCapacity(initialCapacity);
	//设置缓存最大容量为100,超过100之后就会按照LRU最近最少使用算法来移除缓存项
	cacheBuilder.maximumSize(maximumSize);

	if (recordStats) {
		//设置要统计缓存的命中率
		cacheBuilder.recordStats();
	}
	//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
	LoadingCache<K, V> loadingCache = cacheBuilder.build(new CacheLoader<K, V>() {
		@Override
		public V load(K key) throws Exception {
			return null;
		}
	});

	return loadingCache;

	//		for (int i = 0; i < 20; i++)
	//		{
	//			//从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
	//			Long student = studentCache.get("p");
	//			System.out.println(student);
	//			//休眠1秒
	//			TimeUnit.SECONDS.sleep(1);
	//		}

	//		System.out.println("cache stats:");
	//最后打印缓存的命中率等 情况
	//		System.out.println(studentCache.stats().toString());
}
 
Example 12
Source File: CaffeineCacheFromContext.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public static <K, V> Cache<K, V> newCaffeineCache(CacheContext context) {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  context.caffeine = builder;

  if (context.initialCapacity != InitialCapacity.DEFAULT) {
    builder.initialCapacity(context.initialCapacity.size());
  }
  if (context.isRecordingStats()) {
    builder.recordStats();
  }
  if (context.maximumSize != Maximum.DISABLED) {
    if (context.weigher == CacheWeigher.DEFAULT) {
      builder.maximumSize(context.maximumSize.max());
    } else {
      builder.weigher(context.weigher);
      builder.maximumWeight(context.maximumWeight());
    }
  }
  if (context.expiryType() != CacheExpiry.DISABLED) {
    builder.expireAfter(context.expiry);
  }
  if (context.afterAccess != Expire.DISABLED) {
    builder.expireAfterAccess(context.afterAccess.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.afterWrite != Expire.DISABLED) {
    builder.expireAfterWrite(context.afterWrite.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.refresh != Expire.DISABLED) {
    builder.refreshAfterWrite(context.refresh.timeNanos(), TimeUnit.NANOSECONDS);
  }
  if (context.expires() || context.refreshes()) {
    SerializableTicker ticker = context.ticker()::read;
    builder.ticker(ticker);
  }
  if (context.keyStrength == ReferenceType.WEAK) {
    builder.weakKeys();
  } else if (context.keyStrength == ReferenceType.SOFT) {
    throw new IllegalStateException();
  }
  if (context.isWeakValues()) {
    builder.weakValues();
  } else if (context.isSoftValues()) {
    builder.softValues();
  }
  if (context.cacheExecutor != CacheExecutor.DEFAULT) {
    builder.executor(context.executor);
  }
  if (context.cacheScheduler != CacheScheduler.DEFAULT) {
    builder.scheduler(context.scheduler);
  }
  if (context.removalListenerType != Listener.DEFAULT) {
    builder.removalListener(context.removalListener);
  }
  if (context.isStrongKeys() && !context.isAsync()) {
    builder.writer(context.cacheWriter());
  }
  if (context.isAsync()) {
    if (context.loader == null) {
      context.asyncCache = builder.buildAsync();
    } else {
      context.asyncCache = builder.buildAsync(
          context.isAsyncLoading ? context.loader.async() : context.loader);
    }
    context.cache = context.asyncCache.synchronous();
  } else if (context.loader == null) {
    context.cache = builder.build();
  } else {
    context.cache = builder.build(context.loader);
  }

  @SuppressWarnings("unchecked")
  Cache<K, V> castedCache = (Cache<K, V>) context.cache;
  RandomSeedEnforcer.resetThreadLocalRandom();
  return castedCache;
}