com.google.common.cache.Cache Java Examples

The following examples show how to use com.google.common.cache.Cache. 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: OnlineClientListServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public Set<ClientData> getListeningClientsData(ConfigMeta meta) {
    Cache<String, Long> cache = onlineClients.get(meta);
    if (cache == null) {
        return ImmutableSet.of();
    }

    Set<ClientData> clients = Sets.newHashSetWithExpectedSize((int)cache.size());
    for (Map.Entry<String, Long> entry : cache.asMap().entrySet()) {
        String ip = entry.getKey();
        long version = entry.getValue();
        ClientData client = new ClientData(ip, version);
        clients.add(client);
    }

    return clients;
}
 
Example #2
Source File: PrometheusSink.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Override
public void processRecord(MetricsRecord record) {
  final String[] sources = MetricsUtil.splitRecordSource(record);

  if (sources.length > 2) {
    final String source = String.format("%s/%s/%s", getTopologyName(), sources[1], sources[2]);

    Map<String, Double> sourceCache = metricsCache.getIfPresent(source);
    if (sourceCache == null) {
      final Cache<String, Double> newSourceCache = createCache();
      sourceCache = newSourceCache.asMap();
    }

    sourceCache.putAll(processMetrics(record.getMetrics()));
    metricsCache.put(source, sourceCache);
  } else {
    LOG.log(Level.SEVERE, "Unexpected metrics source: " + record.getSource());
  }
}
 
Example #3
Source File: MetaDataEndpointImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public void clearTableFromCache(RpcController controller, ClearTableFromCacheRequest request,
        RpcCallback<ClearTableFromCacheResponse> done) {
    byte[] schemaName = request.getSchemaName().toByteArray();
    byte[] tableName = request.getTableName().toByteArray();
    try {
        byte[] tenantId = request.getTenantId().toByteArray();
        byte[] key = SchemaUtil.getTableKey(tenantId, schemaName, tableName);
        ImmutableBytesPtr cacheKey = new ImmutableBytesPtr(key);
        Cache<ImmutableBytesPtr, PTable> metaDataCache =
                GlobalCache.getInstance(this.env).getMetaDataCache();
        metaDataCache.invalidate(cacheKey);
    } catch (Throwable t) {
        logger.error("incrementTableTimeStamp failed", t);
        ProtobufUtil.setControllerException(controller,
            ServerUtil.createIOException(SchemaUtil.getTableName(schemaName, tableName), t));
    }
}
 
Example #4
Source File: TestSchemaGeneratorProcessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheNewEntries() throws StageException {
  SchemaGeneratorConfig config = new SchemaGeneratorConfig();
  config.enableCache = true;
  config.cacheKeyExpression = "key"; // Constant

  ProcessorRunner runner = new ProcessorRunner.Builder(SchemaGeneratorDProcessor.class, new SchemaGeneratorProcessor(config))
    .addOutputLane("a")
    .build();
  runner.runInit();

  // Cache is empty at the begging
  Cache<String, String> cache = (Cache<String, String>) runner.getContext().getStageRunnerSharedMap().get(SchemaGeneratorProcessor.CACHE_KEY);
  Assert.assertNotNull(cache);
  Assert.assertNull(cache.getIfPresent("key"));

  Record record = RecordCreator.create();
  record.set(Field.create(Field.Type.LIST_MAP, ImmutableMap.of(
    "a", Field.create(Field.Type.STRING, "Arvind")
  )));

  runner.runProcess(ImmutableList.of(record));

  // Now a new key should exist for this record in teh cache
  Assert.assertNotNull(cache.getIfPresent("key"));
}
 
Example #5
Source File: RemoveEntryTask.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
public RemoveEntryTask(final Cache<Long, byte[]> payloadCache,
                       final PublishPayloadLocalPersistence localPersistence,
                       final BucketLock bucketLock,
                       final Queue<RemovablePayload> removablePayloads,
                       final long removeDelay,
                       final ConcurrentHashMap<Long, AtomicLong> referenceCounter,
                       final long taskMaxDuration) {

    this.payloadCache = payloadCache;
    this.localPersistence = localPersistence;
    this.bucketLock = bucketLock;
    this.removablePayloads = removablePayloads;
    this.removeDelay = removeDelay;
    this.referenceCounter = referenceCounter;
    this.taskMaxDuration = taskMaxDuration;
}
 
Example #6
Source File: CacheFactoryTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void getCache()
{
    String cacheName = "test";
    final Cache<Object, Object> cache = new NullCache<>();
    final CacheProvider virtualHost = mock(CacheProvider.class, withSettings().extraInterfaces(VirtualHost.class));
    when(virtualHost.getNamedCache(cacheName)).thenReturn(cache);
    final Subject subject = new Subject();
    subject.getPrincipals().add(new VirtualHostPrincipal((VirtualHost<?>) virtualHost));
    subject.setReadOnly();

    Cache<String, String> actualCache = Subject.doAs(subject,
                                               (PrivilegedAction<Cache<String, String>>) () -> CacheFactory.getCache(cacheName,
                                                                                                                     null));
    assertSame(actualCache, cache);
    verify(virtualHost).getNamedCache(cacheName);
}
 
Example #7
Source File: HandlerToPreparePlan.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public HandlerToPreparePlan(
    QueryContext context,
    SqlNode sqlNode,
    SqlToPlanHandler handler,
    Cache<Long, PreparedPlan> planCache,
    String sql,
    AttemptObserver observer,
    SqlHandlerConfig config) {
  this.context = context;
  this.sqlNode = sqlNode;
  this.handler = handler;
  this.planCache = planCache;
  this.sql = sql;
  this.observer = observer;
  this.config = config;
}
 
Example #8
Source File: FluentSupplierTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheGuava() {
	Cache<Object, Integer> cache = CacheBuilder.newBuilder()
		       .maximumSize(1000)
		       .expireAfterWrite(10, TimeUnit.MINUTES)
		       .build();

	called=0;
	Supplier<Integer> fn = FluentFunctions.of(this::getOne)
												  .name("myFunction")
												  .memoize((key,f)->cache.get(key,()->f.apply(key)));
	fn.get();
	fn.get();
	fn.get();

	assertThat(called,equalTo(1));


}
 
Example #9
Source File: HMSCache.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Build instance of {@link HMSCache}
 * @return {@link HMSCache}
 */
@SuppressWarnings("unchecked")
public HMSCache build() throws StageException {
  Utils.checkArgument(
      !cacheTypes.isEmpty(),
      "Invalid HMSCache Configuration, Should support at least one type of cache"
  );

  Map<HMSCacheType, Cache<String, Optional<HMSCacheSupport.HMSCacheInfo>>> cacheMap = new HashMap<>();
  CacheBuilder cacheBuilder = CacheBuilder.newBuilder();

  if (maxCacheSize > 0) {
    cacheBuilder.maximumSize(maxCacheSize);
  }

  for (HMSCacheType type : cacheTypes) {
    cacheMap.put(type, cacheBuilder.build());
  }
  return new HMSCache(cacheMap);
}
 
Example #10
Source File: GraphqlHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
public GraphqlHandler(Distributor distributor, URI publicUri) {
  this.distributor = Objects.requireNonNull(distributor);
  this.publicUri = Objects.requireNonNull(publicUri);

  GraphQLSchema schema = new SchemaGenerator()
    .makeExecutableSchema(buildTypeDefinitionRegistry(), buildRuntimeWiring());

  Cache<String, PreparsedDocumentEntry> cache = CacheBuilder.newBuilder()
    .maximumSize(1024)
    .build();

  graphQl = GraphQL.newGraphQL(schema)
    .preparsedDocumentProvider((executionInput, computeFunction) -> {
      try {
        return cache.get(executionInput.getQuery(), () -> computeFunction.apply(executionInput));
      } catch (ExecutionException e) {
        if (e.getCause() instanceof RuntimeException) {
          throw (RuntimeException) e.getCause();
        } else if (e.getCause() != null) {
          throw new RuntimeException(e.getCause());
        }
        throw new RuntimeException(e);
      }
    })
    .build();
}
 
Example #11
Source File: TestMapMaker.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
  Cache<String, String> makeMap = CacheBuilder.newBuilder().weakKeys().maximumSize(10).build();

  for (int i = 0; i < 7; i++) {
    makeMap.put("a" + i, "V" + i);
  }
  System.out.println(Joiner.on(", ").withKeyValueSeparator("=").join(makeMap.asMap()));
  for (int i = 0; i < 1; i++) {
    makeMap.put("b" + i, "V" + i);
  }
  System.out.println(Joiner.on(", ").withKeyValueSeparator("=").join(makeMap.asMap()));
  System.out.println(makeMap.asMap().containsKey("a1"));
  System.out.println(makeMap.asMap().containsKey("a4"));
  System.out.println(makeMap.asMap().containsKey("a5"));
  System.out.println(makeMap.asMap().get("a1"));
  System.out.println(makeMap.asMap().get("a4"));
  System.out.println(makeMap.asMap().get("a5"));

}
 
Example #12
Source File: GuavaLevel1CacheProvider.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T get(String cacheName, String key) {
    try {
        Cache<String, Object> cache = getCacheHolder(cacheName);
        if (cache != null) {
            Object result = cache.get(key, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return _NULL;
                }
            });
            if (result != null && !_NULL.equals(result)) {
                return (T) result;
            }
        }
    } catch (Exception e) {
        logger.warn("get LEVEL1 cache error", e);
    }
    return null;
}
 
Example #13
Source File: LongPollingStoreImpl.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void run() {
    try {
        String oldName = Thread.currentThread().getName();
        Thread.currentThread().setName("qconfig-config-listener-clearUp");
        try {
            for (Cache<Listener, Listener> cache : listenerMappings.values()) {
                cache.cleanUp();
            }
        } finally {
            Thread.currentThread().setName(oldName);
        }
    } catch (Exception e) {
        logger.error("schedule listener clear up error", e);
    }
}
 
Example #14
Source File: LocatableResolver.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<ResolverResult> resolveWithCache(@Nonnull FDBRecordContext context,
                                                           @Nonnull ScopedValue<String> scopedName,
                                                           @Nonnull Cache<ScopedValue<String>, ResolverResult> directoryCache,
                                                           @Nonnull ResolverCreateHooks hooks) {
    ResolverResult value = directoryCache.getIfPresent(scopedName);
    if (value != null) {
        return CompletableFuture.completedFuture(value);
    }

    return context.instrument(
            FDBStoreTimer.Events.DIRECTORY_READ,
            runAsyncBorrowingReadVersion(context, childContext -> readOrCreateValue(childContext, scopedName.getData(), hooks))
    ).thenApply(fetched -> {
        directoryCache.put(scopedName, fetched);
        return fetched;
    });
}
 
Example #15
Source File: GuavaLevel1CacheProvider.java    From azeroth with Apache License 2.0 5 votes vote down vote up
private Cache<String, Object> getAndNotexistsCreateCache(String cacheName) {
    Cache<String, Object> cache = caches.get(cacheName);
    if (cache != null) { return cache; }
    synchronized (caches) {
        if ((cache = caches.get(cacheName)) != null) { return cache; }
        cache = CacheBuilder.newBuilder().maximumSize(maxSize)
                .expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS).build();
        caches.put(cacheName, cache);
    }
    return cache;
}
 
Example #16
Source File: Driver.java    From batfish with Apache License 2.0 5 votes vote down vote up
private static Cache<NetworkSnapshot, Map<String, VendorConfiguration>>
    buildVendorConfigurationCache() {
  return CacheBuilder.newBuilder()
      .softValues()
      .maximumSize(MAX_CACHED_VENDOR_CONFIGURATIONS)
      .build();
}
 
Example #17
Source File: BBDecoderTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void str8Caching()
{
    String testString = "Test";
    BBEncoder encoder = new BBEncoder(64);
    encoder.writeStr8(testString);
    encoder.writeStr8(testString);
    ByteBuffer buffer = encoder.buffer();

    BBDecoder decoder = new BBDecoder();
    decoder.init(buffer);
    Cache<Binary, String> original  = BBDecoder.getStringCache();
    Cache<Binary, String> cache = CacheBuilder.newBuilder().maximumSize(2).build();
    try
    {
        BBDecoder.setStringCache(cache);

        String decodedString1 = decoder.readStr8();
        String decodedString2 = decoder.readStr8();

        assertThat(testString, is(equalTo(decodedString1)));
        assertThat(testString, is(equalTo(decodedString2)));
        assertSame(decodedString1, decodedString2);
    }
    finally
    {
        cache.cleanUp();
        BBDecoder.setStringCache(original);
    }
}
 
Example #18
Source File: DefaultCacheRegistry.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void invalidate(InvalidationEvent event) {
    // Invalidate the actual cache.
    Cache<String, ?> cache = _cache.get();
    if (cache != null) {
        if (event.hasKeys()) {
            cache.invalidateAll(event.getKeys());
        } else {
            cache.invalidateAll();
        }
    }
    notifyListeners(event);
}
 
Example #19
Source File: OpenFlowRuleProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
private Cache<Long, InternalCacheEntry> createBatchCache() {
    return CacheBuilder.newBuilder()
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .removalListener((RemovalNotification<Long, InternalCacheEntry> notification) -> {
                if (notification.getCause() == RemovalCause.EXPIRED) {
                    providerService.batchOperationCompleted(notification.getKey(),
                                                            notification.getValue().failedCompletion());
                }
            }).build();
}
 
Example #20
Source File: KnownHostBotVerifierImpl.java    From webcrawler-verifier with MIT License 5 votes vote down vote up
public KnownHostBotVerifierImpl(@NotNull CrawlerData crawlerData,
                                @NotNull ReverseDnsVerifier dnsVerifier,
                                @NotNull Cache<String, BotCheckerResult> dnsResultCache) {
    this.crawlerData = crawlerData;
    this.dnsVerifier = dnsVerifier;
    this.cache = dnsResultCache;
}
 
Example #21
Source File: HotKeyListener.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public void onComplete(EVCacheEvent e) {
    if(!enableThrottleHotKeys.get()) return;
    final String appName = e.getAppName();
    final Cache<String, Integer> cache = getCache(appName);
    if(cache == null) return;

    for(EVCacheKey evcKey : e.getEVCacheKeys()) {
        final String key = evcKey.getKey();
        Integer val = cache.getIfPresent(key);
        if(val != null) {
            cache.put(key, Integer.valueOf(val.intValue() - 1));
        }
    }
}
 
Example #22
Source File: CoreUnitDispatcher.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
private Cache<String, String> getOrCreateJobLock() {
    if (jobLock == null) {
        this.jobLock = CacheBuilder.newBuilder()
                .concurrencyLevel(getIntProperty("dispatcher.job_lock_concurrency_level"))
                .expireAfterWrite(getIntProperty("dispatcher.job_lock_expire_seconds"),
                        TimeUnit.SECONDS)
                .build();
    }
    return jobLock;
}
 
Example #23
Source File: TrellisServiceBundler.java    From trellis with Apache License 2.0 5 votes vote down vote up
static IOService buildIoService(final AppConfiguration config, final Jdbi jdbi) {
    final long cacheSize = config.getJsonld().getCacheSize();
    final long hours = config.getJsonld().getCacheExpireHours();
    final Cache<String, String> cache = newBuilder().maximumSize(cacheSize).expireAfterAccess(hours, HOURS).build();
    final TrellisCache<String, String> profileCache = new TrellisCache<>(cache);
    final NamespaceService namespaceService = useTriplestore(config) ?
        new FileNamespaceService(config.getNamespaces()) : new DBNamespaceService(jdbi);
    final RDFaWriterService htmlSerializer = new DefaultRdfaWriterService(namespaceService,
            config.getAssets().getTemplate(), config.getAssets().getCss(), config.getAssets().getJs(),
            config.getAssets().getIcon());
    return new JenaIOService(namespaceService, htmlSerializer, profileCache,
            config.getJsonld().getContextWhitelist(), config.getJsonld().getContextDomainWhitelist(),
            config.getUseRelativeIris());
}
 
Example #24
Source File: GuavaLevel1CacheProvider.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public boolean set(String cacheName,String key,Object value){
	if(value == null)return true;
	Cache<String, Object> cache = getCacheHolder(cacheName);
	if(cache != null){
		cache.put(key, value);
	}
	return true;
}
 
Example #25
Source File: StringCache.java    From ApiManager with GNU Affero General Public License v3.0 5 votes vote down vote up
public Cache<String, String> getCache(){
    if (cache == null) {
           cache = CacheBuilder.newBuilder()
                   .initialCapacity(10)
                   .concurrencyLevel(5)
                   .expireAfterWrite(10 * 60, TimeUnit.SECONDS)
                   .build();
       }
       return cache;
}
 
Example #26
Source File: ManagedCache.java    From mercury with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain a ManagedCache instance
 *
 * @param name of cache store
 * @param expiryMs in milliseconds
 * @param maxItems maximum number of cached objects
 * @return cache instance
 */
public synchronized static ManagedCache createCache(String name, long expiryMs, long maxItems) {
    ManagedCache managedCache = getInstance(name);
    if (managedCache != null) {
        return managedCache;
    }
    long expiryTimer = Math.max(expiryMs, MIN_EXPIRY);
    Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(maxItems).expireAfterWrite(expiryTimer, TimeUnit.MILLISECONDS).build();
    // create cache
    managedCache = new ManagedCache(cache, name, expiryTimer, maxItems);
    cacheCollection.put(name, managedCache);
    log.info("Created cache ({}), expiry {} ms, maxItems={}", name, expiryTimer, maxItems);
    return managedCache;
}
 
Example #27
Source File: AbstractTableJdbcSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() {
  if (sshTunnelService != null){
    sshTunnelService.stop();
  }
  boolean interrupted = shutdownExecutorIfNeeded();
  //Invalidate all the thread cache so that all statements/result sets are properly closed.
  toBeInvalidatedThreadCaches.forEach(Cache::invalidateAll);
  //Closes all connections
  Optional.ofNullable(connectionManager).ifPresent(ConnectionManager::closeAll);
  jdbcUtil.closeQuietly(hikariDataSource);
  if (interrupted) {
    Thread.currentThread().interrupt();
  }
}
 
Example #28
Source File: SchemaCache.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
private Schema<?> get(final Class<?> cls, Cache<Class<?>, Schema<?>> cache) {
    try {
        return cache.get(cls, new Callable() {
            @Override
            public Object call() throws Exception {
                return RuntimeSchema.createFrom(cls);
            }
        });
    } catch (ExecutionException e) {
        return null;
    }
}
 
Example #29
Source File: InMemoryCachingPluginResolutionServiceClient.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <K, V> Response<V> getResponse(Key<K> key, Cache<Key<K>, Response<V>> cache, Factory<Response<V>> responseFactory, Transformer<Key<K>, ? super Response<V>> keyGenerator) {
    Response<V> response = key == null ? null : cache.getIfPresent(key);
    if (response != null) {
        return response;
    } else {
        response = responseFactory.create();
        if (!response.isError()) {
            Key<K> actualKey = keyGenerator.transform(response);
            cache.put(actualKey, response);
        }
        return response;
    }
}
 
Example #30
Source File: SimpleVirtualFlowRuleStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Modified
public void modified(ComponentContext context) {

    readComponentConfiguration(context);

    // Reset Cache and copy all.
    Cache<Long, SettableFuture<CompletedBatchOperation>> prevFutures = pendingFutures;
    pendingFutures = CacheBuilder.newBuilder()
            .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
            .removalListener(new TimeoutFuture())
            .build();

    pendingFutures.putAll(prevFutures.asMap());
}