To put an object to the cache call method Cache.put(Object key, Object value) of the interface cacheonix.cache.Cache. When the number unique keys exeeds the maximum cache size, the least recently used elements are evicted from the cache. The example below shows how to put an object to the cache:
package com.cacheonix.examples.cache; import junit.framework.TestCase; import cacheonix.cache.Cache; import cacheonix.cache.CacheManager; /** * Tester for Cache. */ public final class CacheTest extends TestCase { /** * MAX_SIZE is configured for {@link TEST_CACHE} in the cacheonix-config.xml. */ private static final int MAX_SIZE = 1000; private static final String TEST_CACHE = "local.test.cache"; private static final Object KEY = "key"; private static final Object VALUE = "value"; private static final Object VALUE_1 = "value1"; private static final Object VALUE_2 = "value2"; private CacheManager cacheManager; /** * Tests putting an object to the cache. */ public void testPut() { final Cache cache = cacheManager.getCache(TEST_CACHE); // Put an object to the cache final Object replacedValue1 = cache.put(KEY, VALUE_1); assertNull(replacedValue1); assertEquals(VALUE_1, cache.get(KEY)); // Put another object using the same key final Object replacedValue2 = cache.put(KEY, VALUE_2); assertEquals(VALUE_1, replacedValue2); assertEquals(VALUE_2, cache.get(KEY)); } /** * Tests putting an object to the cache evicts objects * when number of unique puts exceeds maximum cache size. */ public void testPutEvictsObjects() { final Cache cache = cacheManager.getCache(TEST_CACHE); // Put objects to the cache with number objects exeeding maximum cache size for (int i = 0; i < MAX_SIZE * 2; i++) { final String index = Integer.toString(i); cache.put(KEY + index, VALUE + index); } assertEquals(MAX_SIZE, cache.size()); } /** * Sets up the fixture. This method is called before a test is executed. */ protected void setUp() throws Exception { super.setUp(); cacheManager = CacheManager.getInstance(); } /** * Tears down the fixture. This method is called after a test is executed. */ protected void tearDown() throws Exception { // Cache manager has to be shutdown upon application exit cacheManager.shutdown(); super.tearDown(); } }
Labels
(None)
