Java Code Examples for org.cache2k.Cache#put()

The following examples show how to use org.cache2k.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: ExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void manualExpireWithEntryProcessor_sharp() {
  Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(LONG_DELTA, TimeUnit.MILLISECONDS)
    .refreshAhead(true)
    .loader(new CacheLoader<Integer, Integer>() {
      @Override
      public Integer load(final Integer key) throws Exception {
        return 4711;
      }
    })
    .build();
  c.put(1,2);
  c.invoke(1, new EntryProcessor<Integer, Integer, Object>() {
    @Override
    public Object process(final MutableCacheEntry<Integer, Integer> e) throws Exception {
      e.setExpiryTime(-millis());
      return null;
    }
  });
  assertFalse(c.containsKey(1));
}
 
Example 2
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void manualExpire_nowIsh_doesTriggerRefresh() throws Exception {
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(5, TimeUnit.MINUTES)
    .refreshAhead(true)
    .loader(new CacheLoader<Integer, Integer>() {
      @Override
      public Integer load(final Integer key) throws Exception {
        return 4711;
      }
    })
    .build();
  c.put(1,2);
  c.expireAt(1, millis() + TestingParameters.MINIMAL_TICK_MILLIS);
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getRefreshCount() > 0;
    }
  });
}
 
Example 3
Source File: ListenerTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void customExecutor() {
  final AtomicInteger _counter = new AtomicInteger();
  Cache<Integer, Integer> c =
    Cache2kBuilder.of(Integer.class, Integer.class)
      .addAsyncListener(new CacheEntryCreatedListener<Integer, Integer>() {
        @Override
        public void onEntryCreated(final Cache<Integer, Integer> cache, final CacheEntry<Integer, Integer> entry) {
        }
      })
      .asyncListenerExecutor(new Executor() {
        @Override
        public void execute(final Runnable command) {
          _counter.incrementAndGet();
        }
      })
      .build();
  c.put(1,2);
  c.close();
  assertEquals(1, _counter.get());
}
 
Example 4
Source File: BasicCacheTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testNBulkPeekAll() {
  Cache<Integer, Integer> c = freshCache(Integer.class, Integer.class, null, 100, -1);
  c.put(1, 1);
  c.put(2, 2);
  Set<Integer> _requestedKeys = new HashSet<Integer>(Arrays.asList(2, 3));
  Map<Integer, Integer> m = c.peekAll(_requestedKeys);
  assertEquals(1, m.size());
  assertEquals(2, (int) m.get((int) 2));
}
 
Example 5
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void manualExpire_aboutNow() {
  Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class)
    .expireAfterWrite(LONG_DELTA, TimeUnit.MILLISECONDS)
    .build();
  c.put(1,2);
  assertTrue(c.containsKey(1));
  c.expireAt(1, millis());
  assertFalse(c.containsKey(1));
  statistics()
    .putCount.expect(1)
    .expiredCount.expect(1)
    .expectAllZero();
}
 
Example 6
Source File: Cache2kBuilderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * When using classes for the type information, there is no generic type information.
 * There is an ugly cast to (Object) needed to strip the result and be able to cast
 * to the correct one.
 */
@Test
public void collectionValueClass() {
  Cache<Long, List<String>> c =
    (Cache<Long, List<String>>) (Object) Cache2kBuilder.of(Long.class, List.class).eternal(true).build();
  c.put(123L, new ArrayList<String>());
  c.close();
}
 
Example 7
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void manualExpire_exception() {
  Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .eternal(true)
    .build();
  c.put(1,2);
  c.expireAt(1, FUTURE_TIME);
}
 
Example 8
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void noPrefetchWhenPresent() {
  Cache<Integer,Integer> c = cacheWithLoader();
  c.put(123, 3);
  c.prefetch(123);
  assertTrue(latestInfo(c).getAsyncLoadsStarted() == 0);
}
 
Example 9
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testImmediateExpire() {
  final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class)
    .loader(new IntCountingCacheSource())
    .expireAfterWrite(0, TimeUnit.MILLISECONDS)
    .keepDataAfterExpired(false)
    .sharpExpiry(true)
    .build();
  c.get(1);
  assertEquals(0, getInfo().getSize());
  c.put(3,3);
  assertEquals(0, getInfo().getSize());
  assertEquals(0, getInfo().getPutCount());
}
 
Example 10
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void loadAndExpireRaceNoGone() {
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .keepDataAfterExpired(false)
    .expireAfterWrite(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS)
    .loader(new CacheLoader<Integer, Integer>() {
      @Override
      public Integer load(final Integer key) throws Exception {
        sleep(100);
        return key;
      }
    })
    .build();
  c.put(1,1);
  c.reloadAll(toIterable(1), null);
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getLoadCount() > 0;
    }
  });
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getSize() == 0;
    }
  });
}
 
Example 11
Source File: BasicTimingTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testBigCacheTimingWithExpiry() {
  final int _CACHE_SIZE = 1000000;
  Cache<Integer,Integer> c =
    Cache2kBuilder.of(Integer.class, Integer.class)
      .entryCapacity(_CACHE_SIZE)
      .expireAfterWrite(5, TimeUnit.MINUTES)
      .build();
  for (int i = 0; i < _CACHE_SIZE; i++) {
    c.put(i, i);
  }
  assertNotNull(c.toString());
}
 
Example 12
Source File: BasicCacheTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplace() {
  Cache<Integer, Integer> c = freshCache(Integer.class, Integer.class, null, 100, -1);
  assertFalse(c.replace(1, 1));
  c.put(1, 1);
  assertTrue(c.replace(1, 2));
  assertTrue(c.replace(1, 1));
  assertFalse(c.replace(2, 2));
}
 
Example 13
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void prefetchAll_partiallyPresent_listener() {
  final Cache<Integer,Integer> c = cacheWithLoader();
  CompletionWaiter w = new CompletionWaiter();
  c.put(1, 1);
  c.put(2, 2);
  c.prefetchAll(toIterable(1, 2, 3, 4), w);
  assertTrue(isLoadStarted(c));
  w.awaitCompletion();
  assertTrue(c.containsKey(3));
  assertThat("expect 2 started loads, since 1 is in the cache",
    latestInfo(c).getAsyncLoadsStarted(),
    allOf(greaterThanOrEqualTo(2L), lessThanOrEqualTo(3L)));
}
 
Example 14
Source File: OsgiIT.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() {
  CacheManager m = CacheManager.getInstance("testSimple");
  Cache<String, String> c =
    Cache2kBuilder.of(String.class, String.class)
      .manager(m)
      .eternal(true)
      .build();
  c.put("abc", "123");
  assertTrue(c.containsKey("abc"));
  assertEquals("123", c.peek("abc"));
  c.close();
}
 
Example 15
Source File: BasicCacheTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testPeekAndPut() {
  Cache<Integer, Integer> c = freshCache(Integer.class, Integer.class, null, 100, -1);
  c.put(1, 1);
  assertEquals((Integer) 1, c.peekAndPut(1, 2));
  assertEquals((Integer) 2, c.peekAndPut(1, 1));
}
 
Example 16
Source File: JmxSupportTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
/**
 * Construct three caches with multiple issues and check the health string of the manager JMX.
 */
@Test
public void multipleWarnings() throws Exception {
  final String _MANAGER_NAME = getClass().getName() + ".multipleWarnings";
  final String _CACHE_NAME_BAD_HASHING = "cacheWithBadHashing";
  final String _CACHE_NAME_KEY_MUTATION = "cacheWithKeyMutation";
  final String _CACHE_NAME_MULTIPLE_ISSUES = "cacheWithMultipleIssues";
  final String _SUPPRESS1 =  "org.cache2k.Cache/" + _MANAGER_NAME + ":" + _CACHE_NAME_KEY_MUTATION;
  final String _SUPPRESS2 =  "org.cache2k.Cache/" + _MANAGER_NAME + ":" + _CACHE_NAME_MULTIPLE_ISSUES;
  Log.registerSuppression(_SUPPRESS1, new Log.SuppressionCounter());
  Log.registerSuppression(_SUPPRESS2, new Log.SuppressionCounter());
  CacheManager m = CacheManager.getInstance(_MANAGER_NAME);
  Cache _cacheWithBadHashing = Cache2kBuilder.of(Object.class, Object.class)
    .manager(m)
    .name(_CACHE_NAME_BAD_HASHING)
    .eternal(true)
    .build();
  Cache _cacheWithKeyMutation = Cache2kBuilder.of(Object.class, Object.class)
    .manager(m)
    .name(_CACHE_NAME_KEY_MUTATION)
    .eternal(true)
    .entryCapacity(50)
    .build();
  Cache _cacheWithMultipleIssues = Cache2kBuilder.of(Object.class, Object.class)
    .manager(m)
    .name(_CACHE_NAME_MULTIPLE_ISSUES)
    .entryCapacity(50)
    .eternal(true)
    .build();
  for (int i = 0; i < 9; i++) {
    _cacheWithBadHashing.put(new KeyForMutation(), 1);
  }
  for (int i = 0; i < 100; i++) {
    _cacheWithMultipleIssues.put(new KeyForMutation(), 1);
  }
  for (int i = 0; i < 100; i++) {
    KeyForMutation v = new KeyForMutation();
    _cacheWithKeyMutation.put(v, 1);
    _cacheWithMultipleIssues.put(v, 1);
    v.value = 1;
  }
  String _health = (String) server.getAttribute(getCacheManagerObjectName(_MANAGER_NAME), "HealthStatus");
  assertEquals(
    "FAILURE: [cacheWithKeyMutation] hash quality is 0 (threshold: 5); " +
    "FAILURE: [cacheWithMultipleIssues] hash quality is 0 (threshold: 5); " +
    "WARNING: [cacheWithBadHashing] hash quality is 7 (threshold: 20); " +
    "WARNING: [cacheWithKeyMutation] key mutation detected; " +
    "WARNING: [cacheWithMultipleIssues] key mutation detected", _health);
  Log.deregisterSuppression(_SUPPRESS1);
  Log.deregisterSuppression(_SUPPRESS2);
  m.close();
}
 
Example 17
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test
public void manualExpire_refreshAhead_sharp_refresh() {
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(LONG_DELTA, TimeUnit.MILLISECONDS)
    .refreshAhead(true)
    .keepDataAfterExpired(false)
    .loader(new CacheLoader<Integer, Integer>() {
      @Override
      public Integer load(final Integer key) throws Exception {
        return 4711;
      }
    })
    .build();
  c.put(1,2);
  within(LONG_DELTA)
    .work(new Runnable() {
      @Override
      public void run() {
        c.expireAt(1, -millis());
        assertFalse(c.containsKey(1));
        await(new Condition() {
          @Override
          public boolean check() throws Exception {
            return getInfo().getRefreshCount() == 1;
          }
        });
      }
    })
    .check(new Runnable() {
      @Override
      public void run() {
        assertEquals(1, getInfo().getSize());
        c.expireAt(1, ExpiryTimeValues.ETERNAL);
        assertFalse(c.containsKey(1));
        assertEquals(1, getInfo().getSize());
        assertEquals(1, getInfo().getRefreshCount());
        c.expireAt(1, ExpiryTimeValues.REFRESH);
        assertEquals(1, getInfo().getSize());
        await(new Condition() {
          @Override
          public boolean check() throws Exception {
            return getInfo().getRefreshCount() == 2;
          }
        });
      }
    });
}
 
Example 18
Source File: BasicCacheTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test
public void testIteratorOnOneEntryCallNext() {
  Cache<Integer, Integer> c = freshCache(Integer.class, Integer.class, null, 100, -1);
  c.put(47, 11);
  assertEquals((Integer) 11, c.entries().iterator().next().getValue());
}
 
Example 19
Source File: RejectNullValueTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void replaceIfEquals() {
  Cache<Integer, Integer> c = target.cache();
  c.put(KEY, VALUE);
  c.replaceIfEquals(KEY, VALUE, null);
}
 
Example 20
Source File: RejectNullValueTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void replace() {
  Cache<Integer, Integer> c = target.cache();
  c.put(KEY, VALUE);
  c.replace(KEY, null);
}