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

The following examples show how to use com.google.common.cache.Cache#put() . 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 void register(ConfigMeta meta, String ip, long version) {
    Cache<String, Long> cache = onlineClients.get(meta);
    if (cache== null) {
        Cache<String, Long> newCache = CacheBuilder
                .newBuilder()
                .expireAfterWrite(timeout, TimeUnit.MILLISECONDS)
                .build();
        cache = onlineClients.putIfAbsent(meta, newCache);
        if (cache == null) {
            cache = newCache;
        }
    }

    cache.put(ip, version);
}
 
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>> 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 3
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 4
Source File: GuavaCache6.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	RemovalListener<String, String> listener = new RemovalListener<String, String>() {
		public void onRemoval(RemovalNotification<String, String> notification) {
			System.out.println("[" + notification.getKey() + ":" + notification.getValue() + "] is removed!");
		}
	};
	Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build();
	Object value = new Object();
	cache.put("key1", "value1");
	cache.put("key2", "value2");
	cache.put("key3", "value3");
	cache.put("key4", "value3");
	cache.put("key5", "value3");
	cache.put("key6", "value3");
	cache.put("key7", "value3");
	cache.put("key8", "value3");
}
 
Example 5
Source File: GuavaCache8.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).recordStats() // 开启统计信息开关
			.build();
	cache.put("key1", "value1");
	cache.put("key2", "value2");
	cache.put("key3", "value3");
	cache.put("key4", "value4");

	cache.getIfPresent("key1");
	cache.getIfPresent("key2");
	cache.getIfPresent("key3");
	cache.getIfPresent("key4");
	cache.getIfPresent("key5");
	cache.getIfPresent("key6");

	System.out.println(cache.stats()); // 获取统计信息
}
 
Example 6
Source File: InMemoryCachingPluginResolutionServiceClient.java    From Pushjet-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 7
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 8
Source File: GuavaCache1.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    Cache<String,String> cache = CacheBuilder.newBuilder().build();
    cache.put("word","Hello Guava Cache");
    System.out.println(cache.getIfPresent("word"));
    Object xx=cache.getIfPresent("xx");
    System.out.println(xx);
}
 
Example 9
Source File: GuavaCache2.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
	Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).build();
	cache.put("key1", "value1");
	cache.put("key2", "value2");
	cache.put("key3", "value3");
	System.out.println("第一个值:" + cache.getIfPresent("key1"));
	System.out.println("第二个值:" + cache.getIfPresent("key2"));
	System.out.println("第三个值:" + cache.getIfPresent("key3"));
}
 
Example 10
Source File: GuavaCache3.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(2).weakValues().build();
	Object value = new Object();
	cache.put("key1", value);

	value = new Object();// 原对象不再有强引用
	System.gc();
	System.out.println(cache.getIfPresent("key1"));
}
 
Example 11
Source File: GuavaCache4.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void test1() throws InterruptedException {
	Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).expireAfterWrite(300, TimeUnit.SECONDS)
			.build();
	cache.put("key1", "value1");
	int time = 1;
	while (true) {
		System.out.println("第" + time++ + "次取到key1的值为:" + cache.getIfPresent("key1"));
		Thread.sleep(1000);
	}
}
 
Example 12
Source File: MetaDataEndpointImpl.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private PTable buildTable(byte[] key, ImmutableBytesPtr cacheKey, HRegion region,
        long clientTimeStamp) throws IOException, SQLException {
    Scan scan = MetaDataUtil.newTableRowsScan(key, MIN_TABLE_TIMESTAMP, clientTimeStamp);
    RegionScanner scanner = region.getScanner(scan);

    Cache<ImmutableBytesPtr,PTable> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
    try {
        PTable oldTable = metaDataCache.getIfPresent(cacheKey);
        long tableTimeStamp = oldTable == null ? MIN_TABLE_TIMESTAMP-1 : oldTable.getTimeStamp();
        PTable newTable;
        newTable = getTable(scanner, clientTimeStamp, tableTimeStamp);
        if (newTable == null) {
            return null;
        }
        if (oldTable == null || tableTimeStamp < newTable.getTimeStamp()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Caching table "
                        + Bytes.toStringBinary(cacheKey.get(), cacheKey.getOffset(),
                            cacheKey.getLength()) + " at seqNum "
                        + newTable.getSequenceNumber() + " with newer timestamp "
                        + newTable.getTimeStamp() + " versus " + tableTimeStamp);
            }
            metaDataCache.put(cacheKey, newTable);
        }
        return newTable;
    } finally {
        scanner.close();
    }
}
 
Example 13
Source File: LocatableResolverTest.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Test
public void testScopedCaching() {
    KeySpace keySpace = new KeySpace(
            new KeySpaceDirectory("path1", KeyType.STRING, "path1"),
            new KeySpaceDirectory("path2", KeyType.STRING, "path2")
    );

    try (FDBRecordContext context = database.openContext()) {
        final ResolvedKeySpacePath path1 = keySpace.resolveFromKey(context, Tuple.from("path1"));
        final LocatableResolver resolver1 = scopedDirectoryGenerator.apply(database, path1);

        Cache<ScopedValue<String>, Long> cache = CacheBuilder.newBuilder().build();
        cache.put(resolver1.wrap("stuff"), 1L);

        assertThat("values can be read from the cache by scoped string",
                cache.getIfPresent(resolver1.wrap("stuff")), is(1L));
        assertThat("cache misses when looking for unknown name in scope",
                cache.getIfPresent(resolver1.wrap("missing")), equalTo(null));

        final ResolvedKeySpacePath path2 = keySpace.resolveFromKey(context, Tuple.from("path2"));
        final LocatableResolver resolver2 = scopedDirectoryGenerator.apply(database, path2);
        assertThat("cache misses when string is not in this scope",
                cache.getIfPresent(resolver2.wrap("stuff")), equalTo(null));

        final LocatableResolver newResolver = scopedDirectoryGenerator.apply(database, path1);
        assertThat("scoping is determined by value of scope directory, not a reference to it",
                cache.getIfPresent(newResolver.wrap("stuff")), is(1L));
    }
}
 
Example 14
Source File: ConfigFileControllerTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleMessage() throws Exception {
  String someWatchKey = "someWatchKey";
  String anotherWatchKey = "anotherWatchKey";
  String someCacheKey = "someCacheKey";
  String anotherCacheKey = "anotherCacheKey";
  String someValue = "someValue";

  ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
  when(someReleaseMessage.getMessage()).thenReturn(someWatchKey);

  Cache<String, String> cache =
      (Cache<String, String>) ReflectionTestUtils.getField(configFileController, "localCache");
  cache.put(someCacheKey, someValue);
  cache.put(anotherCacheKey, someValue);

  watchedKeys2CacheKey.putAll(someWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
  watchedKeys2CacheKey.putAll(anotherWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));

  cacheKey2WatchedKeys.putAll(someCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
  cacheKey2WatchedKeys.putAll(anotherCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));

  configFileController.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);

  assertTrue(watchedKeys2CacheKey.isEmpty());
  assertTrue(cacheKey2WatchedKeys.isEmpty());
}
 
Example 15
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 16
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 17
Source File: RecordingHiveMetastore.java    From presto with Apache License 2.0 5 votes vote down vote up
private <K, V> V loadValue(Cache<K, V> cache, K key, Supplier<V> valueSupplier)
{
    if (replay) {
        return Optional.ofNullable(cache.getIfPresent(key))
                .orElseThrow(() -> new PrestoException(NOT_FOUND, "Missing entry found for key: " + key));
    }

    V value = valueSupplier.get();
    cache.put(key, value);
    return value;
}
 
Example 18
Source File: UnixGlob.java    From intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether {@code str} matches the glob pattern {@code pattern}. This method may use the
 * {@code patternCache} to speed up the matching process.
 *
 * @param pattern a glob pattern
 * @param str the string to match
 * @param patternCache a cache from patterns to compiled Pattern objects, or {@code null} to skip
 *     caching
 */
private static boolean matches(String pattern, String str, Cache<String, Pattern> patternCache) {
  if (pattern.length() == 0 || str.length() == 0) {
    return false;
  }

  // Common case: **
  if (pattern.equals("**")) {
    return true;
  }

  // Common case: *
  if (pattern.equals("*")) {
    return true;
  }

  // If a filename starts with '.', this char must be matched explicitly.
  if (str.charAt(0) == '.' && pattern.charAt(0) != '.') {
    return false;
  }

  // Common case: *.xyz
  if (pattern.charAt(0) == '*' && pattern.lastIndexOf('*') == 0) {
    return str.endsWith(pattern.substring(1));
  }
  // Common case: xyz*
  int lastIndex = pattern.length() - 1;
  // The first clause of this if statement is unnecessary, but is an
  // optimization--charAt runs faster than indexOf.
  if (pattern.charAt(lastIndex) == '*' && pattern.indexOf('*') == lastIndex) {
    return str.startsWith(pattern.substring(0, lastIndex));
  }

  Pattern regex = patternCache == null ? null : patternCache.getIfPresent(pattern);
  if (regex == null) {
    regex = makePatternFromWildcard(pattern);
    if (patternCache != null) {
      patternCache.put(pattern, regex);
    }
  }
  return regex.matcher(str).matches();
}
 
Example 19
Source File: MetaDataEndpointImpl.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Override
public void dropTable(RpcController controller, DropTableRequest request,
        RpcCallback<MetaDataResponse> done) {
    MetaDataResponse.Builder builder = MetaDataResponse.newBuilder();
    boolean isCascade = request.getCascade();
    byte[][] rowKeyMetaData = new byte[3][];
    String tableType = request.getTableType();
    byte[] schemaName = null;
    byte[] tableName = null;

    try {
        List<Mutation> tableMetadata = ProtobufUtil.getMutations(request);
        MetaDataUtil.getTenantIdAndSchemaAndTableName(tableMetadata, rowKeyMetaData);
        byte[] tenantIdBytes = rowKeyMetaData[PhoenixDatabaseMetaData.TENANT_ID_INDEX];
        schemaName = rowKeyMetaData[PhoenixDatabaseMetaData.SCHEMA_NAME_INDEX];
        tableName = rowKeyMetaData[PhoenixDatabaseMetaData.TABLE_NAME_INDEX];
        // Disallow deletion of a system table
        if (tableType.equals(PTableType.SYSTEM.getSerializedValue())) {
            builder.setReturnCode(MetaDataProtos.MutationCode.UNALLOWED_TABLE_MUTATION);
            builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
            done.run(builder.build());
            return;
        }
        List<byte[]> tableNamesToDelete = Lists.newArrayList();
        byte[] parentTableName = MetaDataUtil.getParentTableName(tableMetadata);
        byte[] lockTableName = parentTableName == null ? tableName : parentTableName;
        byte[] lockKey = SchemaUtil.getTableKey(tenantIdBytes, schemaName, lockTableName);
        byte[] key =
                parentTableName == null ? lockKey : SchemaUtil.getTableKey(tenantIdBytes,
                    schemaName, tableName);

        HRegion region = env.getRegion();
        MetaDataMutationResult result = checkTableKeyInRegion(key, region);
        if (result != null) {
            done.run(MetaDataMutationResult.toProto(result));
            return;
        }
        List<RowLock> locks = Lists.newArrayList();

        try {
            acquireLock(region, lockKey, locks);
            if (key != lockKey) {
                acquireLock(region, key, locks);
            }
            List<ImmutableBytesPtr> invalidateList = new ArrayList<ImmutableBytesPtr>();
            result =
                    doDropTable(key, tenantIdBytes, schemaName, tableName, parentTableName,
                        PTableType.fromSerializedValue(tableType), tableMetadata,
                        invalidateList, locks, tableNamesToDelete, isCascade);
            if (result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) {
                done.run(MetaDataMutationResult.toProto(result));
                return;
            }
            Cache<ImmutableBytesPtr,PTable> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
            // Commit the list of deletion.
            region.mutateRowsWithLocks(tableMetadata, Collections.<byte[]> emptySet());
            long currentTime = MetaDataUtil.getClientTimeStamp(tableMetadata);
            for (ImmutableBytesPtr ckey : invalidateList) {
                metaDataCache.put(ckey, newDeletedTableMarker(currentTime));
            }
            if (parentTableName != null) {
                ImmutableBytesPtr parentCacheKey = new ImmutableBytesPtr(lockKey);
                metaDataCache.invalidate(parentCacheKey);
            }
            done.run(MetaDataMutationResult.toProto(result));
            return;
        } finally {
            region.releaseRowLocks(locks);
        }
    } catch (Throwable t) {
      logger.error("dropTable failed", t);
        ProtobufUtil.setControllerException(controller,
            ServerUtil.createIOException(SchemaUtil.getTableName(schemaName, tableName), t));
    }
}
 
Example 20
Source File: GuavaLocalCache.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public void put(String cacheName, String key, Object value) {
    Cache<String, Object> cache = getCache(cacheName);
    cache.put(key, value);
}