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

The following examples show how to use com.github.benmanes.caffeine.cache.Caffeine#initialCapacity() . 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: 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 3
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testInitialCapacity_negative() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder();
  try {
    builder.initialCapacity(-1);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 4
Source File: CacheBuilderTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public void testInitialCapacity_setTwice() {
  Caffeine<Object, Object> builder = Caffeine.newBuilder().initialCapacity(16);
  try {
    // even to the same value is not allowed
    builder.initialCapacity(16);
    fail();
  } catch (IllegalStateException expected) {}
}
 
Example 5
Source File: CaffeineCacheFactory.java    From cache2k-benchmark with Apache License 2.0 5 votes vote down vote up
private Caffeine createCache(final int _maxElements) {
  Caffeine b = Caffeine.newBuilder().maximumSize(_maxElements);
  if (sameThreadEviction) {
    b.executor(Runnable::run);
  }
  if (fullEvictionCapacity) {
    b.initialCapacity(_maxElements);
  }
  if (withExpiry) {
    b.expireAfterWrite(2 * 60, TimeUnit.SECONDS);
  }
  return b;
}
 
Example 6
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 7
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;
}