@Test public void removeRecordWithEntryProcessor() { final int ENTRY_COUNT = 10; CachingProvider cachingProvider = HazelcastServerCachingProvider.createCachingProvider(node1); CacheManager cacheManager = cachingProvider.getCacheManager(); CompleteConfiguration<Integer, String> cacheConfig = new MutableConfiguration<Integer, String>().setTypes(Integer.class, String.class); ICache<Integer, String> cache = cacheManager.createCache("MyCache", cacheConfig).unwrap(ICache.class); for (int i = 0; i < ENTRY_COUNT; i++) { cache.put(i * 1000, "Value-" + (i * 1000)); } assertEquals(ENTRY_COUNT, cache.size()); for (int i = 0; i < ENTRY_COUNT; i++) { if (i % 2 == 0) { cache.invoke(i * 1000, new RemoveRecordEntryProcessor()); } } assertEquals(ENTRY_COUNT / 2, cache.size()); }
@Test public void testLatestAccessCacheMergePolicy() { String cacheName = randomMapName(); Config config = newConfig(); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config); TestMemberShipListener memberShipListener = new TestMemberShipListener(1); h2.getCluster().addMembershipListener(memberShipListener); TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1); h2.getLifecycleService().addLifecycleListener(lifeCycleListener); closeConnectionBetween(h1, h2); assertOpenEventually(memberShipListener.latch); assertClusterSizeEventually(1, h1); assertClusterSizeEventually(1, h2); CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1); CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2); CacheManager cacheManager1 = cachingProvider1.getCacheManager(); CacheManager cacheManager2 = cachingProvider2.getCacheManager(); CacheConfig cacheConfig = newCacheConfig(cacheName, LatestAccessCacheMergePolicy.class.getName()); Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig); Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig); // TODO We assume that until here and also while doing get/put, cluster is still splitted. // This assumptions seems fragile due to time sensitivity. cache1.put("key1", "value"); assertEquals("value", cache1.get("key1")); // Access to record // Prevent updating at the same time sleepAtLeastMillis(1); cache2.put("key1", "LatestUpdatedValue"); assertEquals("LatestUpdatedValue", cache2.get("key1")); // Access to record cache2.put("key2", "value2"); assertEquals("value2", cache2.get("key2")); // Access to record // Prevent updating at the same time sleepAtLeastMillis(1); cache1.put("key2", "LatestUpdatedValue2"); assertEquals("LatestUpdatedValue2", cache1.get("key2")); // Access to record assertOpenEventually(lifeCycleListener.latch); assertClusterSizeEventually(2, h1); assertClusterSizeEventually(2, h2); Cache cacheTest = cacheManager1.getCache(cacheName); assertEquals("LatestUpdatedValue", cacheTest.get("key1")); assertEquals("LatestUpdatedValue2", cacheTest.get("key2")); }
/** * Run a task defined by the {@link Runnable} instance with a {@link CachingProvider} making sure * that the caching provider is closed after use. * * @param r task to execute with caching provider */ public static void withCachingProvider(JCacheRunnable r) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); CachingProvider p = Caching.getCachingProvider(new TestClassLoader(tccl)); try { r.run(p); } finally { p.close(); } }
@Test public void testCacheLoader() { final CacheLoader<String, Integer> cacheLoader = new CacheLoader<String, Integer>() { @Override public Integer load(String key) throws CacheLoaderException { return Integer.valueOf(key); } @Override public Map<String, Integer> loadAll(Iterable<? extends String> keys) throws CacheLoaderException { Map<String, Integer> map = new HashMap<>(); for (String key : keys) { map.put(key, Integer.valueOf(key)); } return map; } }; try (CachingProvider cachingProvider = Caching.getCachingProvider(GuavaCachingProvider.class.getName())) { CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, Integer> custom = new MutableConfiguration<>(); custom.setStoreByValue(false); custom.setTypes(String.class, Integer.class); custom.setReadThrough(true); custom.setCacheLoaderFactory( new Factory<CacheLoader<String, Integer>>() { @Override public CacheLoader<String, Integer> create() { return cacheLoader; } }); Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom); assertEquals(Integer.valueOf(1), loadingCache.get("1")); assertEquals(Integer.valueOf(2), loadingCache.get("2")); assertEquals(Integer.valueOf(3), loadingCache.get("3")); Set<String> keys = Sets.newHashSet("4", "5", "6"); Map<String, Integer> map = loadingCache.getAll(keys); assertEquals(3, map.size()); assertEquals(Integer.valueOf(4), map.get("4")); assertEquals(Integer.valueOf(5), map.get("5")); assertEquals(Integer.valueOf(6), map.get("6")); } }
private void executeEntryProcessor( Integer key, EntryProcessor<Integer, String, Void> entryProcessor, String cacheName) { CachingProvider cachingProvider = HazelcastServerCachingProvider.createCachingProvider(node1); CacheManager cacheManager = cachingProvider.getCacheManager(); CompleteConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setTypes(Integer.class, String.class); Cache<Integer, String> cache = cacheManager.createCache(cacheName, config); cache.invoke(key, entryProcessor); }
@Test public void testJCacheGettingStarted() { try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(); Cache<String, String> cache = manager.createCache("testCache", new MutableConfiguration<>())) { cache.put("key", "value"); assertThat(cache.get("key")).isEqualTo("value"); cache.remove("key"); assertThat(cache.get("key")).isNull(); } }
@Test public void testWithoutEhcacheExplicitDependencyCanSpecifyXML() throws Exception { // tag::jsr107UsingXMLConfigExample[] CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager manager = cachingProvider.getCacheManager( // <1> getClass().getResource("/org/ehcache/docs/ehcache-jsr107-config.xml").toURI(), // <2> getClass().getClassLoader()); // <3> Cache<Long, Product> readyCache = manager.getCache("ready-cache", Long.class, Product.class); // <4> // end::jsr107UsingXMLConfigExample[] assertThat(readyCache, notNullValue()); }
@Test public void test_CacheReplicationOperation_serialization() throws Exception { TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1); HazelcastInstance hazelcastInstance = factory.newHazelcastInstance(); try { CachingProvider provider = HazelcastServerCachingProvider.createCachingProvider(hazelcastInstance); CacheManager manager = provider.getCacheManager(); CompleteConfiguration configuration = new MutableConfiguration(); Cache cache1 = manager.createCache("cache1", configuration); Cache cache2 = manager.createCache("cache2", configuration); Cache cache3 = manager.createCache("cache3", configuration); for (int i = 0; i < 1000; i++) { cache1.put("key" + i, i); cache2.put("key" + i, i); cache3.put("key" + i, i); } HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance; Field original = HazelcastInstanceProxy.class.getDeclaredField("original"); original.setAccessible(true); HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy); NodeEngineImpl nodeEngine = impl.node.nodeEngine; CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME); int partitionCount = nodeEngine.getPartitionService().getPartitionCount(); for (int partitionId = 0; partitionId < partitionCount; partitionId++) { CachePartitionSegment segment = cacheService.getSegment(partitionId); CacheReplicationOperation operation = new CacheReplicationOperation(segment, 1); Data serialized = service.toData(operation); try { service.toObject(serialized); } catch (Exception e) { throw new Exception("Partition: " + partitionId, e); } } } finally { factory.shutdownAll(); } }
@Test public void testTemplateOverridingStoreByValue() throws Exception { cacheManager = cachingProvider.getCacheManager( getClass() .getResource("/org/ehcache/docs/ehcache-jsr107-template-override.xml") .toURI(), getClass().getClassLoader()); MutableConfiguration<Long, String> mutableConfiguration = new MutableConfiguration<Long, String>(); mutableConfiguration.setTypes(Long.class, String.class); Cache<Long, String> myCache = null; myCache = cacheManager.createCache("anyCache", mutableConfiguration); myCache.put(1L, "foo"); assertNotSame("foo", myCache.get(1L)); assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue()); myCache = cacheManager.createCache("byRefCache", mutableConfiguration); myCache.put(1L, "foo"); assertSame("foo", myCache.get(1L)); assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue()); myCache = cacheManager.createCache("weirdCache1", mutableConfiguration); myCache.put(1L, "foo"); assertNotSame("foo", myCache.get(1L)); assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue()); myCache = cacheManager.createCache("weirdCache2", mutableConfiguration); myCache.put(1L, "foo"); assertSame("foo", myCache.get(1L)); assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue()); }
@Override public void stop() { if (cachingProvider != null) { cachingProvider.close(); cachingProvider = null; } }
public static CacheManager createCacheManager( CachingProvider provider, Class invoker, String cacheName, Properties properties) { properties.setProperty("infinispan.jcache.remote.managed_access", "false"); return provider.getCacheManager( URI.create(invoker.getName()), new TestClassLoader(Thread.currentThread().getContextClassLoader()), properties); }
@Test public void testWithoutEhcacheExplicitDependencyAndNoCodeChanges() throws Exception { CacheManager manager = cachingProvider.getCacheManager( getClass() .getResource("/org/ehcache/docs/ehcache-jsr107-template-override.xml") .toURI(), getClass().getClassLoader()); // tag::jsr107SupplementWithTemplatesExample[] MutableConfiguration<Long, String> mutableConfiguration = new MutableConfiguration<Long, String>(); mutableConfiguration.setTypes(Long.class, String.class); // <1> Cache<Long, String> anyCache = manager.createCache("anyCache", mutableConfiguration); // <2> CacheRuntimeConfiguration<Long, String> ehcacheConfig = (CacheRuntimeConfiguration<Long, String>) anyCache .getConfiguration(Eh107Configuration.class) .unwrap(CacheRuntimeConfiguration.class); // <3> ehcacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(); // <4> Cache<Long, String> anotherCache = manager.createCache("byRefCache", mutableConfiguration); assertFalse(anotherCache.getConfiguration(Configuration.class).isStoreByValue()); // <5> MutableConfiguration<String, String> otherConfiguration = new MutableConfiguration<String, String>(); otherConfiguration.setTypes(String.class, String.class); otherConfiguration.setExpiryPolicyFactory( CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)); // <6> Cache<String, String> foosCache = manager.createCache("foos", otherConfiguration); // <7> CacheRuntimeConfiguration<Long, String> foosEhcacheConfig = (CacheRuntimeConfiguration<Long, String>) foosCache .getConfiguration(Eh107Configuration.class) .unwrap(CacheRuntimeConfiguration.class); foosEhcacheConfig.getExpiry().getExpiryForCreation(42L, "Answer!").getAmount(); // <8> CompleteConfiguration<String, String> foosConfig = foosCache.getConfiguration(CompleteConfiguration.class); try { final Factory<ExpiryPolicy> expiryPolicyFactory = foosConfig.getExpiryPolicyFactory(); ExpiryPolicy expiryPolicy = expiryPolicyFactory.create(); // <9> throw new AssertionError("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // Expected } // end::jsr107SupplementWithTemplatesExample[] assertThat( ehcacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L)); assertThat( foosEhcacheConfig.getExpiry().getExpiryForCreation(42L, "Answer!"), is(new org.ehcache.expiry.Duration(2, TimeUnit.MINUTES))); }
@Test public void testCustomCacheMergePolicy() { String cacheName = randomMapName(); Config config = newConfig(); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config); TestMemberShipListener memberShipListener = new TestMemberShipListener(1); h2.getCluster().addMembershipListener(memberShipListener); TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1); h2.getLifecycleService().addLifecycleListener(lifeCycleListener); closeConnectionBetween(h1, h2); assertOpenEventually(memberShipListener.latch); assertClusterSizeEventually(1, h1); assertClusterSizeEventually(1, h2); CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1); CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2); CacheManager cacheManager1 = cachingProvider1.getCacheManager(); CacheManager cacheManager2 = cachingProvider2.getCacheManager(); CacheConfig cacheConfig = newCacheConfig(cacheName, CustomCacheMergePolicy.class.getName()); Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig); Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig); // TODO We assume that until here and also while doing get/put, cluster is still splitted. // This assumptions seems fragile due to time sensitivity. String key = generateKeyOwnedBy(h1); cache1.put(key, "value"); cache2.put(key, Integer.valueOf(1)); assertOpenEventually(lifeCycleListener.latch); assertClusterSizeEventually(2, h1); assertClusterSizeEventually(2, h2); Cache cacheTest = cacheManager2.getCache(cacheName); assertNotNull(cacheTest.get(key)); assertTrue(cacheTest.get(key) instanceof Integer); }
@After public void tearDown() throws Exception { if (cacheManager != null) { cacheManager.close(); } if (cachingProvider != null) { cachingProvider.close(); } }
public static Cache createCacheWithProperties( CachingProvider provider, Class invoker, String cacheName, Properties properties) { CacheManager manager = provider.getCacheManager( URI.create(invoker.getName()), new TestClassLoader(Thread.currentThread().getContextClassLoader()), properties); properties.setProperty("infinispan.jcache.remote.managed_access", "false"); return manager.createCache(cacheName, new MutableConfiguration()); }
@Test public void testPassThroughCacheMergePolicy() { String cacheName = randomMapName(); Config config = newConfig(); HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config); TestMemberShipListener memberShipListener = new TestMemberShipListener(1); h2.getCluster().addMembershipListener(memberShipListener); TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1); h2.getLifecycleService().addLifecycleListener(lifeCycleListener); closeConnectionBetween(h1, h2); assertOpenEventually(memberShipListener.latch); assertClusterSizeEventually(1, h1); assertClusterSizeEventually(1, h2); CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1); CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2); CacheManager cacheManager1 = cachingProvider1.getCacheManager(); CacheManager cacheManager2 = cachingProvider2.getCacheManager(); CacheConfig cacheConfig = newCacheConfig(cacheName, PassThroughCacheMergePolicy.class.getName()); Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig); Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig); String key = generateKeyOwnedBy(h1); cache1.put(key, "value"); cache2.put(key, "passThroughValue"); assertOpenEventually(lifeCycleListener.latch); assertClusterSizeEventually(2, h1); assertClusterSizeEventually(2, h2); Cache cacheTest = cacheManager2.getCache(cacheName); assertEquals("passThroughValue", cacheTest.get(key)); }
@Test public void testCacheExpired() throws Exception { Configuration<String, String> configuration = new MutableConfiguration<String, String>() .setExpiryPolicyFactory( AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 3))); try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(); Cache<String, String> cache = manager.createCache("testCache", configuration)) { cache.put("key1", "value1"); cache.put("key2", "value2"); TimeUnit.SECONDS.sleep(1); cache.get("key2"); TimeUnit.SECONDS.sleep(2); assertThat(cache.get("key1")).isNull(); assertThat(cache.get("key2")).isEqualTo("value2"); } }
@Ignore @Test public void testWithHazelcastConfiguration() throws Exception { // wrong use!! ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URI uri = classLoader.getResource("hazelcast-jcache.xml").toURI(); try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(uri, classLoader); Cache<String, String> cache = manager.getCache("testCache")) { cache.put("key1", "value1"); cache.put("key2", "value2"); TimeUnit.SECONDS.sleep(1); cache.get("key2"); TimeUnit.SECONDS.sleep(2); assertThat(cache.get("key1")).isNull(); assertThat(cache.get("key2")).isEqualTo("value2"); } }
@Override public void start() { // add application caches module Optional<String> applicationPackage = Optional.fromNullable(settings.getApplicationPackage()); String fullClassName = ClassUtil.buildClassName(applicationPackage, CACHES_CLASS); if (ClassUtil.doesClassExist(fullClassName)) { Class<?> moduleClass = ClassUtil.getClass(fullClassName); if (CachesModule.class.isAssignableFrom(moduleClass)) { CachesModule cachesModule = (CachesModule) ClassUtil.newInstance(moduleClass); if (cachesModule != null) { log.info("Setting up JCache caches in '{}'", cachesModule.getClass().getName()); cachesModule.setup(settings, cachingProvider.getCacheManager()); } } } }
@Before public void setUp() throws Exception { cachingProvider = Caching.getCachingProvider(); cacheManager = cachingProvider.getCacheManager(); }
@Override public void initialize(Class<K> keyClass, Class<T> persistentClass, Properties properties) { super.initialize(keyClass, persistentClass, properties); CachingProvider cachingProvider = Caching.getCachingProvider(properties.getProperty(GORA_DEFAULT_JCACHE_PROVIDER_KEY)); if (properties.getProperty(JCACHE_CACHE_NAMESPACE_PROPERTY_KEY) != null) { goraCacheNamespace = properties.getProperty(JCACHE_CACHE_NAMESPACE_PROPERTY_KEY); } try { this.persistentDataStore = DataStoreFactory.getDataStore(keyClass, persistentClass, new Configuration()); } catch (GoraException ex) { LOG.error("Couldn't initialize persistent DataStore.", ex); } if (properties .getProperty(GORA_DEFAULT_JCACHE_PROVIDER_KEY) .contains(HAZELCAST_SERVER_CACHE_PROVIDER_IDENTIFIER)) { Config config = new ClasspathXmlConfig(properties.getProperty(GORA_DEFAULT_JCACHE_HAZELCAST_CONFIG_KEY)); hazelcastInstance = Hazelcast.newHazelcastInstance(config); } else { try { ClientConfig config = new XmlClientConfigBuilder( properties.getProperty(GORA_DEFAULT_JCACHE_HAZELCAST_CONFIG_KEY)) .build(); hazelcastInstance = HazelcastClient.newHazelcastClient(config); } catch (IOException ex) { LOG.error("Couldn't locate the client side cache provider configuration.", ex); } } Properties providerProperties = new Properties(); providerProperties.setProperty( HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME, hazelcastInstance.getName()); try { manager = cachingProvider.getCacheManager(new URI(goraCacheNamespace), null, providerProperties); } catch (URISyntaxException ex) { LOG.error("Couldn't initialize cache manager to bounded hazelcast instance.", ex); manager = cachingProvider.getCacheManager(); } if (((properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY) != null) && Boolean.valueOf(properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY))) || ((manager.getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass) == null))) { cacheEntryList = new ConcurrentSkipListSet<>(); cacheConfig = new CacheConfig<K, T>(); cacheConfig.setTypes(keyClass, persistentClass); if (properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY) != null) { cacheConfig.setReadThrough( Boolean.valueOf(properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY))); } else { cacheConfig.setReadThrough(true); } if (properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY) != null) { cacheConfig.setWriteThrough( Boolean.valueOf(properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY))); } else { cacheConfig.setWriteThrough(true); } if (properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY) != null) { cacheConfig.setStoreByValue( Boolean.valueOf(properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY) != null) { cacheConfig.setStatisticsEnabled( Boolean.valueOf(properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY) != null) { cacheConfig.setStatisticsEnabled( Boolean.valueOf(properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_POLICY_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setEvictionPolicy( EvictionPolicy.valueOf( properties.getProperty(JCACHE_EVICTION_POLICY_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_MAX_SIZE_POLICY_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setMaximumSizePolicy( EvictionConfig.MaxSizePolicy.valueOf( properties.getProperty(JCACHE_EVICTION_MAX_SIZE_POLICY_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_SIZE_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setSize(Integer.valueOf(properties.getProperty(JCACHE_EVICTION_SIZE_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY) != null) { String expiryPolicyIdentifier = properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY); if (expiryPolicyIdentifier.equals(JCACHE_ACCESSED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new AccessedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_CREATED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new CreatedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_MODIFIED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new ModifiedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_TOUCHED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new TouchedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } } if (properties.getProperty(HAZELCAST_CACHE_IN_MEMORY_FORMAT_PROPERTY_KEY) != null) { String inMemoryFormat = properties.getProperty(HAZELCAST_CACHE_IN_MEMORY_FORMAT_PROPERTY_KEY); if (inMemoryFormat.equals(HAZELCAST_CACHE_BINARY_IN_MEMORY_FORMAT_IDENTIFIER) || inMemoryFormat.equals(HAZELCAST_CACHE_OBJECT_IN_MEMORY_FORMAT_IDENTIFIER) || inMemoryFormat.equals(HAZELCAST_CACHE_NATIVE_IN_MEMORY_FORMAT_IDENTIFIER)) { cacheConfig.setInMemoryFormat(InMemoryFormat.valueOf(inMemoryFormat)); } } cacheConfig.setCacheLoaderFactory( JCacheCacheFactoryBuilder.factoryOfCacheLoader( this.persistentDataStore, keyClass, persistentClass)); cacheConfig.setCacheWriterFactory( JCacheCacheFactoryBuilder.factoryOfCacheWriter( this.persistentDataStore, keyClass, persistentClass)); cache = manager.createCache(persistentClass.getSimpleName(), cacheConfig).unwrap(ICache.class); } else { cache = manager .getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass) .unwrap(ICache.class); this.populateLocalCacheEntrySet(cache); } cache.registerCacheEntryListener( new MutableCacheEntryListenerConfiguration<>( JCacheCacheFactoryBuilder.factoryOfEntryListener( new JCacheCacheEntryListener<K, T>(cacheEntryList)), null, true, true)); LOG.info("JCache Gora datastore initialized successfully."); }
@Test(timeout = 5000L) public void testCacheLoaderAsyncLoadAll() throws InterruptedException { final AtomicInteger loads = new AtomicInteger(); final CacheLoader<String, Integer> cacheLoader = new CacheLoader<String, Integer>() { @Override public Integer load(String key) throws CacheLoaderException { loads.incrementAndGet(); return Integer.valueOf(key); } @Override public Map<String, Integer> loadAll(Iterable<? extends String> keys) throws CacheLoaderException { throw new UnsupportedOperationException("Not supported yet."); } }; final AtomicBoolean completed = new AtomicBoolean(false); final CompletionListener completionListener = new CompletionListener() { @Override public void onCompletion() { completed.set(true); } @Override public void onException(Exception e) { System.err.println(e); } }; try (CachingProvider cachingProvider = Caching.getCachingProvider(GuavaCachingProvider.class.getName())) { CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, Integer> custom = new MutableConfiguration<>(); custom.setStoreByValue(false); custom.setTypes(String.class, Integer.class); custom.setReadThrough(true); custom.setCacheLoaderFactory( new Factory<CacheLoader<String, Integer>>() { @Override public CacheLoader<String, Integer> create() { return cacheLoader; } }); Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom); loadingCache.put("1", 1); loadingCache.put("2", 2); loadingCache.put("3", 3); Set<String> keys = Sets.newHashSet("1", "2", "3", "4", "5", "6"); loadingCache.loadAll(keys, false, completionListener); while (!completed.get()) { Thread.sleep(250); } assertEquals(3, loads.getAndSet(0)); completed.set(false); loadingCache.loadAll(keys, true, completionListener); while (!completed.get()) { Thread.sleep(250); } assertEquals(6, loads.get()); assertEquals(Integer.valueOf(1), loadingCache.getAndRemove("1")); assertEquals(Integer.valueOf(2), loadingCache.getAndRemove("2")); assertEquals(Integer.valueOf(3), loadingCache.getAndRemove("3")); assertEquals(Integer.valueOf(4), loadingCache.getAndRemove("4")); assertEquals(Integer.valueOf(5), loadingCache.getAndRemove("5")); assertEquals(Integer.valueOf(6), loadingCache.getAndRemove("6")); } }