Java Code Examples for com.github.benmanes.caffeine.cache.Cache#put()
The following examples show how to use
com.github.benmanes.caffeine.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: WriteBehindCacheWriterTest.java From caffeine with Apache License 2.0 | 6 votes |
@Test public void givenCacheUpdate_writeBehindIsCalled() { AtomicBoolean writerCalled = new AtomicBoolean(false); // Given this cache... Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder() .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>() .bufferTime(1, TimeUnit.SECONDS) .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo)) .writeAction(entries -> writerCalled.set(true)) .build()) .build(); // When this cache update happens ... cache.put(1L, ZonedDateTime.now()); // Then the write behind action is called Awaitility.await().untilTrue(writerCalled); }
Example 2
Source File: WriteBehindCacheWriterTest.java From caffeine with Apache License 2.0 | 6 votes |
@Test public void givenCacheUpdateOnMultipleKeys_writeBehindIsCalled() { AtomicBoolean writerCalled = new AtomicBoolean(false); AtomicInteger numberOfEntries = new AtomicInteger(0); // Given this cache... Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder() .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>() .bufferTime(1, TimeUnit.SECONDS) .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo)) .writeAction(entries -> { numberOfEntries.set(entries.size()); writerCalled.set(true); }).build()) .build(); // When these cache updates happen ... cache.put(1L, ZonedDateTime.now()); cache.put(2L, ZonedDateTime.now()); cache.put(3L, ZonedDateTime.now()); // Then the write behind action gets 3 entries to write Awaitility.await().untilTrue(writerCalled); Assert.assertEquals(3, numberOfEntries.intValue()); }
Example 3
Source File: AbstractCacheManager.java From Alpine with Apache License 2.0 | 5 votes |
/** * Adds an object to cache. * @param key the unique identifier of the object to put into cache * @param object the object to put into cache. * @since 1.5.0 */ public void put(final String key, final Object object) { Cache<String, Object> cache = typeMap.get(object.getClass()); if (cache == null) { cache = buildCache(); typeMap.put(object.getClass(), cache); } cache.put(key, object); }
Example 4
Source File: Demo.java From banyan with MIT License | 5 votes |
public static void test1() { Cache<String, double[][]> cache = Caffeine.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); String key = "name"; double[][] v = cache.getIfPresent(key); double[][] v1 = new double[0][0]; if (null == v) { cache.put(key, v1); } while (true) { try { Thread.sleep(1000); System.err.println(cache.getIfPresent(key)); } catch (InterruptedException e) { e.printStackTrace(); } } // // double[][] d1 = {{1, 2}, {3, 4}}; // double[][] d2 = new double[d1.length][d1[0].length]; // copy(d1, d2); // // System.out.println(d2[1][0]); }
Example 5
Source File: WriteBehindCacheWriterTest.java From caffeine with Apache License 2.0 | 5 votes |
@Test public void givenMultipleCacheUpdatesOnSameKey_writeBehindIsCalledWithMostRecentTime() { AtomicBoolean writerCalled = new AtomicBoolean(false); AtomicInteger numberOfEntries = new AtomicInteger(0); AtomicReference<ZonedDateTime> timeInWriteBehind = new AtomicReference<>(); // Given this cache... Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder() .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>() .bufferTime(1, TimeUnit.SECONDS) .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo)) .writeAction(entries -> { // We might get here before the cache has been written to, // so just wait for the next time we are called if (entries.isEmpty()) { return; } numberOfEntries.set(entries.size()); ZonedDateTime zonedDateTime = entries.values().iterator().next(); timeInWriteBehind.set(zonedDateTime); writerCalled.set(true); }).build()) .build(); // When these cache updates happen ... cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 0, ZoneId.systemDefault())); cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 100, ZoneId.systemDefault())); cache.put(1L, ZonedDateTime.of(2016, 6, 26, 8, 0, 0, 300, ZoneId.systemDefault())); ZonedDateTime mostRecentTime = ZonedDateTime.of( 2016, 6, 26, 8, 0, 0, 500, ZoneId.systemDefault()); cache.put(1L, mostRecentTime); // Then the write behind action gets 1 entry to write with the most recent time Awaitility.await().untilTrue(writerCalled); Assert.assertEquals(1, numberOfEntries.intValue()); Assert.assertEquals(mostRecentTime, timeInWriteBehind.get()); }
Example 6
Source File: CacheGenerator.java From caffeine with Apache License 2.0 | 5 votes |
@SuppressWarnings({"deprecation", "unchecked", "BoxedPrimitiveConstructor"}) private void populate(CacheContext context, Cache<Integer, Integer> cache) { if (context.population.size() == 0) { return; } int maximum = (int) Math.min(context.maximumSize(), context.population.size()); int first = BASE + (int) Math.min(0, context.population.size()); int last = BASE + maximum - 1; int middle = Math.max(first, BASE + ((last - first) / 2)); context.disableRejectingCacheWriter(); for (int i = 0; i < maximum; i++) { Map.Entry<Integer, Integer> entry = INTS.get(i); // Reference caching (weak, soft) require unique instances for identity comparison Integer key = context.isStrongKeys() ? entry.getKey() : new Integer(BASE + i); Integer value = context.isStrongValues() ? entry.getValue() : new Integer(-key); if (key == first) { context.firstKey = key; } if (key == middle) { context.middleKey = key; } if (key == last) { context.lastKey = key; } cache.put(key, value); context.original.put(key, value); context.ticker().advance(context.advance.timeNanos(), TimeUnit.NANOSECONDS); } context.enableRejectingCacheWriter(); if (context.writer() == Writer.MOCKITO) { reset(context.cacheWriter()); } }
Example 7
Source File: CacheMetricsCollectorTest.java From client_java with Apache License 2.0 | 5 votes |
@Test public void cacheExposesMetricsForHitMissAndEviction() throws Exception { Cache<String, String> cache = Caffeine.newBuilder().maximumSize(2).recordStats().executor(new Executor() { @Override public void execute(Runnable command) { // Run cleanup in same thread, to remove async behavior with evictions command.run(); } }).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, "caffeine_cache_hit_total", "users", 1.0); assertMetric(registry, "caffeine_cache_miss_total", "users", 2.0); assertMetric(registry, "caffeine_cache_requests_total", "users", 3.0); assertMetric(registry, "caffeine_cache_eviction_total", "users", 2.0); }
Example 8
Source File: CaffeineTest.java From cache2k-benchmark with Apache License 2.0 | 5 votes |
@Test public void test() { Cache c = Caffeine.newBuilder().maximumWeight(1000).weigher(new Weigher<Object, Object>() { @Override public int weigh(final Object key, final Object value) { return value.hashCode() & 0x7f; } }).build(); c.put(1, 123); c.put(1, 512); c.put(1, 0); }
Example 9
Source File: CaffeineCacheImpl.java From jboot with Apache License 2.0 | 4 votes |
protected void putData(Cache cache, Object key, CaffeineCacheObject value) { value.setCachetime(System.currentTimeMillis()); cache.put(key, value); }
Example 10
Source File: TestCaffeineCache.java From lucene-solr with Apache License 2.0 | 4 votes |
@Test public void testTimeDecay() { Cache<Integer, String> cacheDecay = Caffeine.newBuilder() .executor(Runnable::run) .maximumSize(20) .build(); for (int i = 1; i < 21; i++) { cacheDecay.put(i, Integer.toString(i)); } Map<Integer, String> itemsDecay; // Now increase the freq count for 5 items for (int i = 0; i < 5; ++i) { for (int j = 0; j < 10; ++j) { cacheDecay.getIfPresent(i + 13); } } // OK, 13 - 17 should have larger counts and should stick past next few collections cacheDecay.put(22, "22"); cacheDecay.put(23, "23"); cacheDecay.put(24, "24"); cacheDecay.put(25, "25"); itemsDecay = cacheDecay.policy().eviction().get().hottest(10); // 13 - 17 should be in cache, but 11 and 18 (among others) should not. Testing that elements before and // after the ones with increased counts are removed, and all the increased count ones are still in the cache assertNull(itemsDecay.get(11)); assertNull(itemsDecay.get(18)); assertNotNull(itemsDecay.get(13)); assertNotNull(itemsDecay.get(14)); assertNotNull(itemsDecay.get(15)); assertNotNull(itemsDecay.get(16)); assertNotNull(itemsDecay.get(17)); // Testing that all the elements in front of the ones with increased counts are gone for (int idx = 26; idx < 32; ++idx) { cacheDecay.put(idx, Integer.toString(idx)); } //Surplus count should be at 0 itemsDecay = cacheDecay.policy().eviction().get().hottest(10); assertNull(itemsDecay.get(20)); assertNull(itemsDecay.get(24)); assertNotNull(itemsDecay.get(13)); assertNotNull(itemsDecay.get(14)); assertNotNull(itemsDecay.get(15)); assertNotNull(itemsDecay.get(16)); assertNotNull(itemsDecay.get(17)); }
Example 11
Source File: RemoteDatastoreSessionCache.java From extended-objects with Apache License 2.0 | 4 votes |
private <C extends AbstractRemotePropertyContainer<S>, S extends AbstractPropertyContainerState> void update(long id, C propertyContainer, Cache<Long, C> cache) { cache.invalidate(propertyContainer.getId()); propertyContainer.updateId(id); cache.put(id, propertyContainer); }