Java Code Examples for com.google.common.cache.Cache#getIfPresent()

The following examples show how to use com.google.common.cache.Cache#getIfPresent() . 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: TextUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<String> process(){
	TextIndex textIndex = getTextIndex();
	FieldValue value = getValue();

	Cache<FieldValue, List<String>> termTokenCache = CacheUtil.getValue(textIndex, TextUtil.termTokenCaches, TextUtil.termTokenCacheLoader);

	List<String> tokens = termTokenCache.getIfPresent(value);
	if(tokens == null){
		String string = value.asString();

		tokens = TextUtil.tokenize(textIndex, string);

		termTokenCache.put(value, tokens);
	}

	return tokens;
}
 
Example 2
Source File: TextUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<String> process(){
	TextIndex textIndex = getTextIndex();
	FieldValue value = getValue();

	Cache<FieldValue, List<String>> textTokenCache = CacheUtil.getValue(textIndex, TextUtil.textTokenCaches, TextUtil.textTokenCacheLoader);

	List<String> tokens = textTokenCache.getIfPresent(value);
	if(tokens == null){
		String string = TextUtil.normalize(textIndex, value.asString());

		tokens = TextUtil.tokenize(textIndex, string);

		textTokenCache.put(value, tokens);
	}

	return tokens;
}
 
Example 3
Source File: LocatableResolver.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup the String that maps to the provided value within the scope of the path that this object was constructed with.
 *
 * @param timer the {@link FDBStoreTimer} used for collecting metrics
 * @param value the value of the mapping to lookup
 * @return a future for the name that maps to this value
 * @throws NoSuchElementException if the value is not found
 */
@Nonnull
public CompletableFuture<String> reverseLookup(@Nullable FDBStoreTimer timer, @Nonnull Long value) {
    Cache<ScopedValue<Long>, String> inMemoryReverseCache = database.getReverseDirectoryInMemoryCache();
    String cachedValue = inMemoryReverseCache.getIfPresent(wrap(value));
    if (cachedValue != null) {
        return CompletableFuture.completedFuture(cachedValue);
    }

    return readReverse(timer, value)
            .thenApply(maybeRead ->
                    maybeRead.map(read -> {
                        inMemoryReverseCache.put(wrap(value), read);
                        return read;
                    }).orElseThrow(() -> new NoSuchElementException("reverse lookup of " + wrap(value))));
}
 
Example 4
Source File: SubQueryIterator.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
public SubQueryIterator(JointIndexQuery.Subquery subQuery, IndexSerializer indexSerializer, BackendTransaction tx,
                        Cache<JointIndexQuery.Subquery, List<Object>> indexCache, int limit,
                        Function<Object, ? extends JanusGraphElement> function, List<Object> otherResults) {
    this.subQuery = subQuery;
    this.indexCache = indexCache;
    List<Object> cacheResponse = indexCache.getIfPresent(subQuery);
    Stream<?> stream;
    if (cacheResponse != null) {
        stream = cacheResponse.stream();
    } else {
        try {
            currentIds = new ArrayList<>();
            profiler = QueryProfiler.startProfile(subQuery.getProfiler(), subQuery);
            isTimerRunning = true;
            stream = indexSerializer.query(subQuery, tx).peek(r -> currentIds.add(r));
        } catch (Exception e) {
            throw new JanusGraphException("Could not call index", e.getCause());
        }
    }
    elementIterator = stream.filter(e -> otherResults == null || otherResults.contains(e)).limit(limit).map(function).map(r -> (JanusGraphElement) r).iterator();
}
 
Example 5
Source File: MetaDataEndpointImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private PTable loadTable(RegionCoprocessorEnvironment env, byte[] key,
    ImmutableBytesPtr cacheKey, long clientTimeStamp, long asOfTimeStamp)
    throws IOException, SQLException {
    HRegion region = env.getRegion();
    Cache<ImmutableBytesPtr,PTable> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
    PTable table = metaDataCache.getIfPresent(cacheKey);
    // We always cache the latest version - fault in if not in cache
    if (table != null || (table = buildTable(key, cacheKey, region, asOfTimeStamp)) != null) {
        return table;
    }
    // if not found then check if newer table already exists and add delete marker for timestamp
    // found
    if (table == null
            && (table = buildDeletedTable(key, cacheKey, region, clientTimeStamp)) != null) {
        return table;
    }
    return null;
}
 
Example 6
Source File: CacheMetricsCollectorTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheExposesMetricsForHitMissAndEviction() throws Exception {
    Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).recordStats().build();
    CollectorRegistry registry = new CollectorRegistry();

    CacheMetricsCollector collector = new CacheMetricsCollector().register(registry);
    collector.addCache("users", cache);

    cache.getIfPresent("user1");
    cache.getIfPresent("user1");
    cache.put("user1", "First User");
    cache.getIfPresent("user1");

    // Add to cache to trigger eviction.
    cache.put("user2", "Second User");
    cache.put("user3", "Third User");
    cache.put("user4", "Fourth User");

    assertMetric(registry, "guava_cache_hit_total", "users", 1.0);
    assertMetric(registry, "guava_cache_miss_total", "users", 2.0);
    assertMetric(registry, "guava_cache_requests_total", "users", 3.0);
    assertMetric(registry, "guava_cache_eviction_total", "users", 2.0);
}
 
Example 7
Source File: ConnectionPropertiesTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private static Connection getConnection(JdbcMeta m, String id) throws Exception {
  Field f = JdbcMeta.class.getDeclaredField("connectionCache");
  f.setAccessible(true);
  //noinspection unchecked
  Cache<String, Connection> connectionCache = (Cache<String, Connection>) f.get(m);
  return connectionCache.getIfPresent(id);
}
 
Example 8
Source File: ListReEncryptableContainerKeys.java    From sfs with Apache License 2.0 5 votes vote down vote up
protected Observable<PersistentContainer> loadContainer(VertxContext<Server> vertxContext, PersistentAccount persistentAccount, String containerId, Cache<String, PersistentContainer> containerCache) {
    PersistentContainer persistentContainer = containerCache.getIfPresent(containerId);
    if (persistentContainer != null) {
        return just(persistentContainer);
    } else {
        return just(containerId)
                .flatMap(new LoadContainer(vertxContext, persistentAccount))
                .map(Optional::get)
                .map(persistentContainer1 -> {
                    containerCache.put(containerId, persistentContainer1);
                    return persistentContainer1;
                });
    }
}
 
Example 9
Source File: ListReEncryptableContainerKeys.java    From sfs with Apache License 2.0 5 votes vote down vote up
protected Observable<PersistentAccount> loadAccount(VertxContext<Server> vertxContext, String accountId, Cache<String, PersistentAccount> accountCache) {
    PersistentAccount persistentAccount = accountCache.getIfPresent(accountId);
    if (persistentAccount != null) {
        return just(persistentAccount);
    } else {
        return just(accountId)
                .flatMap(new LoadAccount(vertxContext))
                .map(Optional::get)
                .map(persistentAccount1 -> {
                    accountCache.put(accountId, persistentAccount1);
                    return persistentAccount1;
                });
    }
}
 
Example 10
Source File: FileMetadata.java    From rubix with Apache License 2.0 5 votes vote down vote up
void deleteFiles(Cache<String, FileMetadata> cache)
{
  /*
   * Cases of races when thread T1 trying to add new entry to cache and T2 is removing deleting data for same
   * 1. T2 DeleteFiles |in parallel to| T1 Create FileMetada : Safe, T1 will create new mdfile and start from blank state
   * 2. T2 DeleteFiles |in parallel to| T1 added entry to cache: Safe, T1 still did not load mdfile.
   * 3. T2 DeleteFiles |in parallel to| T1 refreshBitmap:
   *          3.1. T2 gets lock first -> deletes data -> T1 refreshes (maybe twice as T2 sets needsRfresh): => Safe
   *          3.2. T1 refreshes -> T2 deletes -> T2 sets needsRefresh => next T1 operation refreshes
   *                          One operation on T1 would fail in read in RRC but CachingInputStream will handle failure
   */
  Lock lock = stripes.get(getRemotePath());
  try {
    lock.lock();

    File mdFile = new File(mdFilePath);
    mdFile.delete();

    File localFile = new File(localPath);
    localFile.delete();
  }
  finally {
    lock.unlock();
  }

  FileMetadata newEntry = cache.getIfPresent(getRemotePath());
  if (newEntry != null) {
    newEntry.setNeedsRefresh();
  }
}
 
Example 11
Source File: AbstractConfig.java    From apollo with Apache License 2.0 5 votes vote down vote up
private <T> T getValueFromCache(String key, Function<String, T> parser, Cache<String, T> cache, T defaultValue) {
  T result = cache.getIfPresent(key);

  if (result != null) {
    return result;
  }

  return getValueAndStoreToCache(key, parser, cache, defaultValue);
}
 
Example 12
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Implements a threadsafe addition to the message map
 */
private void addMessageToMap(TransferableChatMessage msg) {
    String channelId = msg.getChannelId();
    //as guava cache is synchronized, maybe this is not necessary
    synchronized (messageMap){
        //get all users (sessions) present in the channel where the message goes to
        Cache<String, TransferableChatMessage> sessionsInChannel = heartbeatMap.getIfPresent(channelId);
        if(sessionsInChannel != null) {
            for(String sessionId : sessionsInChannel.asMap().keySet()) {
                TransferableChatMessage tcm = sessionsInChannel.getIfPresent(sessionId);
                String sessionKey = tcm.getId();
                try {
                    Map<String, List<TransferableChatMessage>> channelMap = messageMap.get(sessionKey, () -> {
                        return new HashMap<String, List<TransferableChatMessage>>();
                    });

                    if(channelMap.get(channelId) == null) {
                        channelMap.put(channelId, new ArrayList<TransferableChatMessage>());
                    }
                    channelMap.get(channelId).add(msg);

                    log.debug("Added chat message to channel={}, sessionKey={}", channelId, sessionKey);
                } catch(Exception e){
                    log.warn("Failed to add chat message to channel={}, sessionKey={}", channelId, sessionKey);
                }
            }
        }
    }
}
 
Example 13
Source File: RemoteMetaTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private static Connection getConnection(JdbcMeta m, String id) throws Exception {
  Field f = JdbcMeta.class.getDeclaredField("connectionCache");
  f.setAccessible(true);
  //noinspection unchecked
  Cache<String, Connection> connectionCache = (Cache<String, Connection>) f.get(m);
  return connectionCache.getIfPresent(id);
}
 
Example 14
Source File: HotKeyListener.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public void onError(EVCacheEvent e, Throwable t) {
    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 15
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Implements a threadsafe addition to the message map
 */
private void addMessageToMap(TransferableChatMessage msg) {
    String channelId = msg.getChannelId();
    //as guava cache is synchronized, maybe this is not necessary
    synchronized (messageMap){
        //get all users (sessions) present in the channel where the message goes to
        Cache<String, TransferableChatMessage> sessionsInChannel = heartbeatMap.getIfPresent(channelId);
        if(sessionsInChannel != null) {
            for(String sessionId : sessionsInChannel.asMap().keySet()) {
                TransferableChatMessage tcm = sessionsInChannel.getIfPresent(sessionId);
                String sessionKey = tcm.getId();
                try {
                    Map<String, List<TransferableChatMessage>> channelMap = messageMap.get(sessionKey, () -> {
                        return new HashMap<String, List<TransferableChatMessage>>();
                    });

                    if(channelMap.get(channelId) == null) {
                        channelMap.put(channelId, new ArrayList<TransferableChatMessage>());
                    }
                    channelMap.get(channelId).add(msg);

                    log.debug("Added chat message to channel={}, sessionKey={}", channelId, sessionKey);
                } catch(Exception e){
                    log.warn("Failed to add chat message to channel={}, sessionKey={}", channelId, sessionKey);
                }
            }
        }
    }
}
 
Example 16
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 17
Source File: CachedGridEntry.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static CachedGridEntry getOrCreateEntry(World world, int gridX, int gridZ, int primerChunkX, int primerChunkZ) {
    Cache<Long, CachedGridEntry> currentValue = gridEntryCache.get(world);
    if (currentValue == null) {
        currentValue = createGridCache();
        gridEntryCache.put(world, currentValue);
    }
    Long gridEntryKey = (long) gridX << 32 | gridZ & 0xFFFFFFFFL;
    CachedGridEntry gridEntry = currentValue.getIfPresent(gridEntryKey);
    if (gridEntry == null) {
        gridEntry = new CachedGridEntry(world, gridX, gridZ, primerChunkX, primerChunkZ);
        currentValue.put(gridEntryKey, gridEntry);
    }
    return gridEntry;
}
 
Example 18
Source File: SimpleBGPExtensionProviderContext.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public <T> T getSharedReference(final T object) {
    final Cache<Object, Object> cache = SimpleBGPExtensionProviderContext.this.cacheRef.get();

    @SuppressWarnings("unchecked")
    final T ret = (T) cache.getIfPresent(object);
    if (ret == null) {
        cache.put(object, object);
        return object;
    }

    return ret;
}
 
Example 19
Source File: TestXceiverClientManager.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testFreeByReference() throws IOException {
  OzoneConfiguration conf = new OzoneConfiguration();
  ScmClientConfig clientConfig = conf.getObject(ScmClientConfig.class);
  clientConfig.setMaxSize(1);
  String metaDir = GenericTestUtils.getTempPath(
      TestXceiverClientManager.class.getName() + UUID.randomUUID());
  conf.set(HDDS_METADATA_DIR_NAME, metaDir);
  XceiverClientManager clientManager =
      new XceiverClientManager(conf, clientConfig, null);
  Cache<String, XceiverClientSpi> cache =
      clientManager.getClientCache();

  ContainerWithPipeline container1 =
      storageContainerLocationClient.allocateContainer(
          SCMTestUtils.getReplicationType(conf),
          HddsProtos.ReplicationFactor.ONE,
          OzoneConsts.OZONE);
  XceiverClientSpi client1 = clientManager
      .acquireClient(container1.getPipeline());
  Assert.assertEquals(1, client1.getRefcount());
  Assert.assertEquals(container1.getPipeline(),
      client1.getPipeline());

  ContainerWithPipeline container2 =
      storageContainerLocationClient.allocateContainer(
          SCMTestUtils.getReplicationType(conf),
          HddsProtos.ReplicationFactor.ONE,
          OzoneConsts.OZONE);
  XceiverClientSpi client2 = clientManager
      .acquireClient(container2.getPipeline());
  Assert.assertEquals(1, client2.getRefcount());
  Assert.assertNotEquals(client1, client2);

  // least recent container (i.e containerName1) is evicted
  XceiverClientSpi nonExistent1 = cache.getIfPresent(
      container1.getContainerInfo().getPipelineID().getId().toString()
          + container1.getContainerInfo().getReplicationType());
  Assert.assertEquals(null, nonExistent1);
  // However container call should succeed because of refcount on the client.
  ContainerProtocolCalls.createContainer(client1,
      container1.getContainerInfo().getContainerID(), null);

  // After releasing the client, this connection should be closed
  // and any container operations should fail
  clientManager.releaseClient(client1, false);

  String expectedMessage = "This channel is not connected.";
  try {
    ContainerProtocolCalls.createContainer(client1,
        container1.getContainerInfo().getContainerID(), null);
    Assert.fail("Create container should throw exception on closed"
        + "client");
  } catch (Exception e) {
    Assert.assertEquals(e.getClass(), IOException.class);
    Assert.assertTrue(e.getMessage().contains(expectedMessage));
  }
  clientManager.releaseClient(client2, false);
}
 
Example 20
Source File: MetaDataEndpointImpl.java    From phoenix with Apache License 2.0 4 votes vote down vote up
private PTable doGetTable(byte[] key, long clientTimeStamp, RowLock rowLock) throws IOException, SQLException {
    ImmutableBytesPtr cacheKey = new ImmutableBytesPtr(key);
    Cache<ImmutableBytesPtr, PTable> metaDataCache =
            GlobalCache.getInstance(this.env).getMetaDataCache();
    PTable table = metaDataCache.getIfPresent(cacheKey);
    // We only cache the latest, so we'll end up building the table with every call if the
    // client connection has specified an SCN.
    // TODO: If we indicate to the client that we're returning an older version, but there's a
    // newer version available, the client
    // can safely not call this, since we only allow modifications to the latest.
    if (table != null && table.getTimeStamp() < clientTimeStamp) {
        // Table on client is up-to-date with table on server, so just return
        if (isTableDeleted(table)) {
            return null;
        }
        return table;
    }
    // Ask Lars about the expense of this call - if we don't take the lock, we still won't get
    // partial results
    // get the co-processor environment
    // TODO: check that key is within region.getStartKey() and region.getEndKey()
    // and return special code to force client to lookup region from meta.
    HRegion region = env.getRegion();
    /*
     * Lock directly on key, though it may be an index table. This will just prevent a table
     * from getting rebuilt too often.
     */
    final boolean wasLocked = (rowLock != null);
    if (!wasLocked) {
        rowLock = region.getRowLock(key);
        if (rowLock == null) {
            throw new IOException("Failed to acquire lock on " + Bytes.toStringBinary(key));
        }
    }
    try {
        // Try cache again in case we were waiting on a lock
        table = metaDataCache.getIfPresent(cacheKey);
        // We only cache the latest, so we'll end up building the table with every call if the
        // client connection has specified an SCN.
        // TODO: If we indicate to the client that we're returning an older version, but there's
        // a newer version available, the client
        // can safely not call this, since we only allow modifications to the latest.
        if (table != null && table.getTimeStamp() < clientTimeStamp) {
            // Table on client is up-to-date with table on server, so just return
            if (isTableDeleted(table)) {
                return null;
            }
            return table;
        }
        // Query for the latest table first, since it's not cached
        table = buildTable(key, cacheKey, region, HConstants.LATEST_TIMESTAMP);
        if (table != null && table.getTimeStamp() < clientTimeStamp) {
            return table;
        }
        // Otherwise, query for an older version of the table - it won't be cached
        return buildTable(key, cacheKey, region, clientTimeStamp);
    } finally {
        if (!wasLocked) rowLock.release();
    }
}