Java Code Examples for com.google.common.cache.CacheBuilder#build()

The following examples show how to use com.google.common.cache.CacheBuilder#build() . 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: PerBuildSyscallCache.java    From bazel with Apache License 2.0 6 votes vote down vote up
public PerBuildSyscallCache build() {
  CacheBuilder<Object, Object> statCacheBuilder = CacheBuilder.newBuilder();
  if (maxStats != UNSET) {
    statCacheBuilder = statCacheBuilder.maximumSize(maxStats);
  }
  CacheBuilder<Object, Object> readdirCacheBuilder = CacheBuilder.newBuilder();
  if (maxReaddirs != UNSET) {
    readdirCacheBuilder = readdirCacheBuilder.maximumSize(maxReaddirs);
  }
  if (concurrencyLevel != UNSET) {
    statCacheBuilder = statCacheBuilder.concurrencyLevel(concurrencyLevel);
    readdirCacheBuilder = readdirCacheBuilder.concurrencyLevel(concurrencyLevel);
  }
  return new PerBuildSyscallCache(statCacheBuilder.build(newStatLoader()),
      readdirCacheBuilder.build(newReaddirLoader()));
}
 
Example 2
Source File: ConfigService.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
public ConfigService(List<ConfigurationProvider> configurationProviders, Authorizer authorizer, long maximumCacheSize, long cacheTtlMillis) {
    this.authorizer = authorizer;
    this.objectMapper = new ObjectMapper();
    if (configurationProviders == null || configurationProviders.size() == 0) {
        throw new IllegalArgumentException("Expected at least one configuration provider");
    }
    this.configurationProviderInfo = Suppliers.memoizeWithExpiration(() -> initContentTypeInfo(configurationProviders), cacheTtlMillis, TimeUnit.MILLISECONDS);
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maximumCacheSize >= 0) {
        cacheBuilder = cacheBuilder.maximumSize(maximumCacheSize);
    }
    if (cacheTtlMillis >= 0) {
        cacheBuilder = cacheBuilder.refreshAfterWrite(cacheTtlMillis, TimeUnit.MILLISECONDS);
    }
    this.configurationCache = cacheBuilder
            .build(new CacheLoader<ConfigurationProviderKey, ConfigurationProviderValue>() {
                @Override
                public ConfigurationProviderValue load(ConfigurationProviderKey key) throws Exception {
                    return initConfigurationProviderValue(key);
                }
            });
}
 
Example 3
Source File: GuavaCacheFactoryBean.java    From spring-cache-demo with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (maximumSize != null) {
      builder.maximumSize(maximumSize);
    }
    if (expireAfterAccessInSeconds != null) {
      builder.expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS);
    }
    if (expireAfterWriteInSeconds != null) {
      builder.expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS);
    }
    
    com.google.common.cache.Cache<Object, Object> guavaCache= builder.build();
    this.cache = new GuavaCache(this.name, guavaCache, this.allowNullValues);
}
 
Example 4
Source File: CachingTableProvider.java    From samza with Apache License 2.0 6 votes vote down vote up
private ReadWriteTable createDefaultCacheTable(String tableId, JavaTableConfig tableConfig) {
  long readTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.READ_TTL_MS, "-1"));
  long writeTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.WRITE_TTL_MS, "-1"));
  long cacheSize = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.CACHE_SIZE, "-1"));

  CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
  if (readTtlMs != -1) {
    cacheBuilder.expireAfterAccess(readTtlMs, TimeUnit.MILLISECONDS);
  }
  if (writeTtlMs != -1) {
    cacheBuilder.expireAfterWrite(writeTtlMs, TimeUnit.MILLISECONDS);
  }
  if (cacheSize != -1) {
    cacheBuilder.maximumSize(cacheSize);
  }

  logger.info(String.format("Creating default cache with: readTtl=%d, writeTtl=%d, maxSize=%d",
      readTtlMs, writeTtlMs, cacheSize));

  GuavaCacheTable cacheTable = new GuavaCacheTable(tableId + "-def-cache", cacheBuilder.build());
  cacheTable.init(this.context);

  return cacheTable;
}
 
Example 5
Source File: GuavaCache.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
public GuavaCache(Properties properties, String prefix) {
    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    String maximumSize = properties.getProperty(prefix + ".maximumSize");
    if (StringUtil.isNotEmpty(maximumSize)) {
        cacheBuilder.maximumSize(Long.parseLong(maximumSize));
    } else {
        cacheBuilder.maximumSize(1000);
    }
    String expireAfterAccess = properties.getProperty(prefix + ".expireAfterAccess");
    if (StringUtil.isNotEmpty(expireAfterAccess)) {
        cacheBuilder.expireAfterAccess(Long.parseLong(expireAfterAccess), TimeUnit.MILLISECONDS);
    }
    String expireAfterWrite = properties.getProperty(prefix + ".expireAfterWrite");
    if (StringUtil.isNotEmpty(expireAfterWrite)) {
        cacheBuilder.expireAfterWrite(Long.parseLong(expireAfterWrite), TimeUnit.MILLISECONDS);
    }
    String initialCapacity = properties.getProperty(prefix + ".initialCapacity");
    if (StringUtil.isNotEmpty(initialCapacity)) {
        cacheBuilder.initialCapacity(Integer.parseInt(initialCapacity));
    }
    CACHE = cacheBuilder.build();
}
 
Example 6
Source File: GuavaCacheFactory.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) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (config.getExpireAfterWrite() > 0) {
        cacheBuilder.expireAfterWrite(config.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    cacheBuilder.maximumSize(config.getCapacity() > 0 ? config.getCapacity() : Long.MAX_VALUE);
    com.google.common.cache.Cache<K, CacheObject<V>> cache = cacheBuilder.build();
    return new GuavaCache<>(cache, config);
}
 
Example 7
Source File: CacheStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() throws IOException
{
  open = true;

  if (numInitCacheLines > maxCacheSize) {
    logger.warn("numInitCacheLines = {} is greater than maxCacheSize = {}, maxCacheSize was set to {}", numInitCacheLines,
        maxCacheSize, numInitCacheLines);
    maxCacheSize = numInitCacheLines;
  }

  CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
  cacheBuilder.maximumSize(maxCacheSize);

  if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_ACCESS) {
    cacheBuilder.expireAfterAccess(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
  } else if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_WRITE) {
    cacheBuilder.expireAfterWrite(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
  }
  cache = cacheBuilder.build();

  if (entryExpiryStrategy == ExpiryType.NO_EVICTION) {
    return;
  }

  this.cleanupScheduler = Executors.newScheduledThreadPool(1);
  cleanupScheduler.scheduleAtFixedRate(new Runnable()
  {
    @Override
    public void run()
    {
      cache.cleanUp();
    }
  }, cacheCleanupIntervalInMillis, cacheCleanupIntervalInMillis, TimeUnit.MILLISECONDS);
}
 
Example 8
Source File: MetaDataVersionStampStoreStateCacheFactory.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public FDBRecordStoreStateCache getCache(@Nonnull FDBDatabase database) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maxSize != UNLIMITED) {
        cacheBuilder.maximumSize(maxSize);
    }
    if (expireAfterAccessMillis != UNLIMITED) {
        cacheBuilder.expireAfterAccess(expireAfterAccessMillis, TimeUnit.MILLISECONDS);
    }
    Cache<SubspaceProvider, FDBRecordStoreStateCacheEntry> cache = cacheBuilder.build();
    return new MetaDataVersionStampStoreStateCache(database, cache);
}
 
Example 9
Source File: AsyncLoadingCache.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
public AsyncLoadingCache(long refreshTimeMillis, long deadlineTimeMillis, long maxSize) {
    this.refreshTimeMillis = refreshTimeMillis;
    this.deadlineTimeMillis = deadlineTimeMillis;
    this.maxSize = maxSize;
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .expireAfterWrite(this.refreshTimeMillis, TimeUnit.MILLISECONDS);
    if (maxSize != UNLIMITED) {
        cacheBuilder.maximumSize(maxSize);
    }
    cache = cacheBuilder.build();
}
 
Example 10
Source File: GuavaCacheFactory.java    From cache2k-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> BenchmarkCache<K, V> createUnspecializedLoadingCache(
  final Class<K> _keyType, final Class<V> _valueType,
  final int _maxElements, final BenchmarkCacheLoader<K, V> _source) {
  MyLoadingBenchmarkCache c = new MyLoadingBenchmarkCache();
  c.size = _maxElements;
  CacheBuilder cb = builder(_maxElements);
  c.cache = cb.build(new CacheLoader<K, V>() {
    @Override
    public V load(final K key) throws Exception {
      return _source.load(key);
    }
  });
  return c;
}
 
Example 11
Source File: SimpleCache.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ConcurrentMap<T, Result> createCache(int maxCacheSize) {
    final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder.concurrencyLevel(64);
    cacheBuilder.initialCapacity(maxCacheSize);
    cacheBuilder.maximumSize(maxCacheSize);
    Cache<T, Result> localCache = cacheBuilder.build();
    ConcurrentMap<T, Result> cache = localCache.asMap();
    return cache;
}
 
Example 12
Source File: DefaultSimpleCache.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Construct a cache using the specified capacity and name.
 * 
 * @param maxItems The cache capacity. 0 = use {@link #DEFAULT_CAPACITY}
 * @param useMaxItems Whether the maxItems value should be applied as a size-cap for the cache.
 * @param cacheName An arbitrary cache name.
 */
@SuppressWarnings("unchecked")
public DefaultSimpleCache(int maxItems, boolean useMaxItems, int ttlSecs, int maxIdleSecs, String cacheName)
{
    if (maxItems == 0)
    {
        maxItems = DEFAULT_CAPACITY;
    }
    else if (maxItems < 0)
    {
        throw new IllegalArgumentException("maxItems may not be negative, but was " + maxItems);
    }
    this.maxItems = maxItems;
    this.useMaxItems = useMaxItems;
    this.ttlSecs = ttlSecs;
    this.maxIdleSecs = maxIdleSecs;
    setBeanName(cacheName);
    
    // The map will have a bounded size determined by the maxItems member variable.
    @SuppressWarnings("rawtypes")
    CacheBuilder builder = CacheBuilder.newBuilder();
    
    if (useMaxItems)
    {
        builder.maximumSize(maxItems);
    }
    if (ttlSecs > 0)
    {
        builder.expireAfterWrite(ttlSecs, TimeUnit.SECONDS);
    }
    if (maxIdleSecs > 0)
    {
        builder.expireAfterAccess(maxIdleSecs, TimeUnit.SECONDS);
    }
    builder.concurrencyLevel(32);
    
    cache = (Cache<K, AbstractMap.SimpleImmutableEntry<K, V>>) builder.build();
}
 
Example 13
Source File: BigQueryTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();

  conf.credentials.getCredentialsProvider(getContext(), issues).ifPresent(provider -> {
    if (issues.isEmpty()) {
      try {
        Optional.ofNullable(provider.getCredentials()).ifPresent(c -> bigQuery = BigQueryDelegate.getBigquery(c, conf.credentials.projectId));
      } catch (IOException e) {
        LOG.error(Errors.BIGQUERY_05.getMessage(), e);
        issues.add(getContext().createConfigIssue(
            Groups.CREDENTIALS.name(),
            "conf.credentials.credentialsProvider",
            Errors.BIGQUERY_05
        ));
      }
    }
  });

  dataSetEval = getContext().createELEval("datasetEL");
  tableNameELEval = getContext().createELEval("tableNameEL");
  rowIdELEval = getContext().createELEval("rowIdExpression");

  CacheBuilder tableIdExistsCacheBuilder = CacheBuilder.newBuilder();
  if (conf.maxCacheSize != -1) {
    tableIdExistsCacheBuilder.maximumSize(conf.maxCacheSize);
  }

  tableIdExistsCache = tableIdExistsCacheBuilder.build(new CacheLoader<TableId, Boolean>() {
    @Override
    public Boolean load(TableId key) throws Exception {
      return bigQuery.getTable(key) != null;
    }
  });
  errorRecordHandler = new DefaultErrorRecordHandler(getContext());

  return issues;
}
 
Example 14
Source File: ConfigurableGuavaCacheManager.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private com.google.common.cache.Cache<Object, SimpleValueWrapper> buildCache(CacheConfig cacheConfig) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if(cacheConfig.getExpireAfterWrite() >= 0) {
        builder.expireAfterWrite(cacheConfig.getExpireAfterWrite(), TimeUnit.MILLISECONDS);
    }
    return builder.build();
}
 
Example 15
Source File: DataStatisticsStoreImpl.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
protected void buildCache() {
  final CacheBuilder<Object, Object> cacheBuilder =
      CacheBuilder.newBuilder().maximumSize(MAX_ENTRIES).expireAfterWrite(
          STATISTICS_CACHE_TIMEOUT,
          TimeUnit.MILLISECONDS);
  cache = cacheBuilder.<ByteArray, Map<String, InternalDataStatistics<?, ?, ?>>>build();
}
 
Example 16
Source File: RateLimiter.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public RateLimiter(int maximumSize, boolean recordStats) {
    CacheBuilder<Object, Object> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(1, DAYS);
    if (maximumSize != NO_MAXIMUM_SIZE) {
        cache.maximumSize(maximumSize);
    }
    if (recordStats) {
        cache.recordStats();
    }
    acquiredRecently = cache.build();
}
 
Example 17
Source File: CacheCounter.java    From neural with MIT License 5 votes vote down vote up
public CacheCounter(long duration, TimeUnit unit) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .expireAfterWrite(duration, unit);
    counter = cacheBuilder.build(new CacheLoader<Long, AtomicLong>() {
        @Override
        public AtomicLong load(Long seconds) throws Exception {
            return new AtomicLong(0);
        }
    });
}
 
Example 18
Source File: CacheManager.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
public static final Cache<String, BlockReader> buildCache(CacheBuilder builder)
{
  if (singleCache != null) {
    singleCache.cleanUp();
  }
  if (enableStats) {
    //todo: when we upgrade to a newer guava version we can use this
    // builder.recordStats();
  }
  singleCache = builder.build();
  return singleCache;
}
 
Example 19
Source File: JdbcTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public JdbcTarget(
    final String schemaNameTemplate,
    final String tableNameTemplate,
    final List<JdbcFieldColumnParamMapping> customMappings,
    final boolean caseSensitive,
    final boolean rollbackOnError,
    final boolean useMultiRowOp,
    int maxPrepStmtParameters,
    final ChangeLogFormat changeLogFormat,
    final int defaultOpCode,
    UnsupportedOperationAction unsupportedAction,
    DuplicateKeyAction duplicateKeyAction,
    HikariPoolConfigBean hikariConfigBean,
    final List<String> customDataSqlStateCodes
) {
  this.jdbcUtil = UtilsProvider.getJdbcUtil();
  this.schemaNameTemplate = schemaNameTemplate;
  this.tableNameTemplate = tableNameTemplate;
  this.customMappings = customMappings;
  this.caseSensitive = caseSensitive;
  this.rollbackOnError = rollbackOnError;
  this.useMultiRowOp = useMultiRowOp;
  this.maxPrepStmtParameters = maxPrepStmtParameters;
  this.changeLogFormat = changeLogFormat;
  this.defaultOpCode = defaultOpCode;
  this.unsupportedAction = unsupportedAction;
  this.duplicateKeyAction = duplicateKeyAction;
  this.hikariConfigBean = hikariConfigBean;
  this.dynamicTableName = jdbcUtil.isElString(tableNameTemplate);
  this.dynamicSchemaName = jdbcUtil.isElString(schemaNameTemplate);
  this.customDataSqlStateCodes = customDataSqlStateCodes;
  this.tableAutoCreate = false;

  CacheBuilder cacheBuilder = CacheBuilder.newBuilder()
      .maximumSize(500)
      .expireAfterAccess(1, TimeUnit.HOURS)
      .removalListener((RemovalListener<SchemaAndTable, JdbcRecordWriter>) removal -> {
        removal.getValue().deinit();
      });

  if(LOG.isDebugEnabled()) {
    cacheBuilder.recordStats();
  }

  this.recordWriters = cacheBuilder.build(new RecordWriterLoader());

  cacheCleaner = new CacheCleaner(this.recordWriters, "JdbcTarget", 10 * 60 * 1000);
}
 
Example 20
Source File: CacheUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
public <K, V> LoadingCache<K, V> buildLoadingCache(CacheLoader<K, V> cacheLoader){
	CacheBuilder<Object, Object> cacheBuilder = newCacheBuilder();

	return cacheBuilder.build(cacheLoader);
}