javax.cache.expiry.Duration Java Examples
The following examples show how to use
javax.cache.expiry.Duration.
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: TouchyJCacheAdapter.java From cache2k with Apache License 2.0 | 6 votes |
@Override public long calculateExpiryTime(K _key, V _value, long _loadTime, CacheEntry<K, V> _oldEntry) { if (_value == null) { return NO_CACHE; } Duration d; if (_oldEntry == null || _oldEntry.getException() != null) { d = policy.getExpiryForCreation(); } else { d = policy.getExpiryForUpdate(); } if (d == null) { return ExpiryTimeValues.NEUTRAL; } if (d.equals(Duration.ETERNAL)) { return ExpiryTimeValues.ETERNAL; } if (d.equals(Duration.ZERO)) { return ExpiryTimeValues.NO_CACHE; } return _loadTime + d.getTimeUnit().toMillis(d.getDurationAmount()); }
Example #2
Source File: IgniteCacheWriteBehindNoUpdateSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); CacheConfiguration<String, Long> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME); ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC); ccfg.setCacheMode(CacheMode.PARTITIONED); ccfg.setBackups(1); ccfg.setReadFromBackup(true); ccfg.setCopyOnRead(false); ccfg.setName(THROTTLES_CACHE_NAME); Duration expiryDuration = new Duration(TimeUnit.MINUTES, 1); ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(expiryDuration)); ccfg.setReadThrough(false); ccfg.setWriteThrough(true); ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory<>(new TestCacheStore())); cfg.setCacheConfiguration(ccfg); return cfg; }
Example #3
Source File: CacheProxy.java From caffeine with Apache License 2.0 | 6 votes |
/** * Sets the access expiration time. * * @param expirable the entry that was operated on * @param currentTimeMS the current time, or 0 if not read yet */ protected final void setAccessExpirationTime(Expirable<?> expirable, long currentTimeMS) { try { Duration duration = expiry.getExpiryForAccess(); if (duration == null) { return; } else if (duration.isZero()) { expirable.setExpireTimeMS(0L); } else if (duration.isEternal()) { expirable.setExpireTimeMS(Long.MAX_VALUE); } else { if (currentTimeMS == 0L) { currentTimeMS = currentTimeMillis(); } long expireTimeMS = duration.getAdjustedTime(currentTimeMS); expirable.setExpireTimeMS(expireTimeMS); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to set the entry's expiration time", e); } }
Example #4
Source File: IgniteCacheNoSyncForGetTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @param atomicityMode Atomicity mode. * @param heapCache Heap cache flag. * @param expiryPlc Expiry policy flag. * @return Cache configuration. */ private CacheConfiguration cacheConfiguration(CacheAtomicityMode atomicityMode, boolean heapCache, boolean expiryPlc) { CacheConfiguration ccfg = new CacheConfiguration(); ccfg.setAtomicityMode(atomicityMode); ccfg.setOnheapCacheEnabled(heapCache); ccfg.setWriteSynchronizationMode(FULL_SYNC); ccfg.setName("testCache"); if (expiryPlc) ccfg.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(Duration.FIVE_MINUTES)); return ccfg; }
Example #5
Source File: TouchyJCacheAdapter.java From cache2k with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public boolean replace(K key, final V oldValue, final V newValue) { checkClosed(); checkNullValue(newValue); checkNullValue(oldValue); return c2kCache.invoke(key, new EntryProcessor<K, V, Boolean>() { @Override public Boolean process(final MutableCacheEntry<K, V> e) { if (e.exists()) { if (oldValue.equals(e.getValue())) { e.setValue(newValue); return true; } else { Duration d = expiryPolicy.getExpiryForAccess(); if (d != null) { e.setExpiryTime(calculateExpiry(d)); } } } return false; } }); }
Example #6
Source File: EhCache107ConfigurationIntegrationDocTest.java From ehcache3 with Apache License 2.0 | 6 votes |
@Test public void basicConfiguration() throws Exception { // tag::basicConfigurationExample[] CachingProvider provider = Caching.getCachingProvider(); // <1> CacheManager cacheManager = provider.getCacheManager(); // <2> MutableConfiguration<Long, String> configuration = new MutableConfiguration<Long, String>() // <3> .setTypes(Long.class, String.class) // <4> .setStoreByValue(false) // <5> .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)); // <6> Cache<Long, String> cache = cacheManager.createCache("jCache", configuration); // <7> cache.put(1L, "one"); // <8> String value = cache.get(1L); // <9> // end::basicConfigurationExample[] assertThat(value, is("one")); }
Example #7
Source File: JCSCache.java From commons-jcs with Apache License 2.0 | 6 votes |
private ICacheElement<K, V> updateElement(final K key, final V v, final Duration duration, final IElementAttributes attrs) { final ICacheElement<K, V> element = new CacheElement<>(name, key, v); if (duration != null) { attrs.setTimeFactorForMilliseconds(1); final boolean eternal = duration.isEternal(); attrs.setIsEternal(eternal); if (!eternal) { attrs.setLastAccessTimeNow(); } // MaxLife = -1 to use IdleTime excepted if jcache.ccf asked for something else } element.setElementAttributes(attrs); return element; }
Example #8
Source File: GridCacheAbstractLocalStoreSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws Exception If failed. */ @Test public void testEvict() throws Exception { Ignite ignite1 = startGrid(1); IgniteCache<Object, Object> cache = ignite1.cache(DEFAULT_CACHE_NAME).withExpiryPolicy(new CreatedExpiryPolicy( new Duration(TimeUnit.MILLISECONDS, 100L))); // Putting entry. for (int i = 0; i < KEYS; i++) cache.put(i, i); // Wait when entry U.sleep(200); // Check that entry is evicted from cache, but local store does contain it. for (int i = 0; i < KEYS; i++) { cache.localEvict(Arrays.asList(i)); assertNull(cache.localPeek(i)); assertEquals(i, (int)LOCAL_STORE_1.load(i).get1()); assertEquals(i, cache.get(i)); } }
Example #9
Source File: CacheProxy.java From caffeine with Apache License 2.0 | 6 votes |
/** * Returns the time when the entry will expire. * * @param created if the write is an insert or update * @return the time when the entry will expire, zero if it should expire immediately, * Long.MIN_VALUE if it should not be changed, or Long.MAX_VALUE if eternal */ protected final long getWriteExpireTimeMS(boolean created) { try { Duration duration = created ? expiry.getExpiryForCreation() : expiry.getExpiryForUpdate(); if (duration == null) { return Long.MIN_VALUE; } else if (duration.isZero()) { return 0L; } else if (duration.isEternal()) { return Long.MAX_VALUE; } return duration.getAdjustedTime(currentTimeMillis()); } catch (Exception e) { logger.log(Level.WARNING, "Failed to get the policy's expiration time", e); return Long.MIN_VALUE; } }
Example #10
Source File: GridCacheUtils.java From ignite with Apache License 2.0 | 6 votes |
/** * @param duration Duration. * @return TTL. */ public static long toTtl(Duration duration) { if (duration == null) return TTL_NOT_CHANGED; if (duration.getDurationAmount() == 0) { if (duration.isEternal()) return TTL_ETERNAL; assert duration.isZero(); return TTL_ZERO; } assert duration.getTimeUnit() != null : duration; return duration.getTimeUnit().toMillis(duration.getDurationAmount()); }
Example #11
Source File: CacheExpiryTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testCacheStatisticsRemoveAll() throws Exception { long _EXPIRY_MILLIS = 3; //cannot be zero or will not be added to the cache ExpiryPolicy policy = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, _EXPIRY_MILLIS)); expiryPolicyServer.setExpiryPolicy(policy); MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>(); config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient)).setStatisticsEnabled(true); Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config); for (int i = 0; i < 100; i++) { cache.put(i, i+100); } //should work with all implementations Thread.sleep(_EXPIRY_MILLIS); cache.removeAll(); assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts")); //Removals does not count expired entries assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals")); }
Example #12
Source File: CacheTtlReadOnlyModeSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** */ private static CacheConfiguration[] getCacheConfigurations() { CacheConfiguration[] cfgs = cacheConfigurations(); List<CacheConfiguration> newCfgs = new ArrayList<>(cfgs.length); for (CacheConfiguration cfg : cfgs) { if (cfg.getAtomicityMode() == CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT) { // Expiry policy cannot be used with TRANSACTIONAL_SNAPSHOT. continue; } cfg.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(SECONDS, EXPIRATION_TIMEOUT))); cfg.setEagerTtl(true); newCfgs.add(cfg); } return newCfgs.toArray(new CacheConfiguration[0]); }
Example #13
Source File: IgniteCacheReadThroughEvictionSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public ExpiryPolicy create() { return new ExpiryPolicy() { @Override public Duration getExpiryForCreation() { return new Duration(TimeUnit.MILLISECONDS, TIMEOUT); } /** {@inheritDoc} */ @Override public Duration getExpiryForAccess() { return new Duration(TimeUnit.MILLISECONDS, TIMEOUT); } /** {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { return new Duration(TimeUnit.MILLISECONDS, TIMEOUT); } }; }
Example #14
Source File: CacheExpiryTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testCacheStatisticsRemoveAllNoneExpired() throws Exception { ExpiryPolicy policy = new CreatedExpiryPolicy(Duration.ETERNAL); expiryPolicyServer.setExpiryPolicy(policy); MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>(); config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient)) .setStatisticsEnabled(true); Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config); for (int i = 0; i < 100; i++) { cache.put(i, i+100); } cache.removeAll(); assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts")); assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals")); }
Example #15
Source File: ExpiryPolicyClient.java From cache2k with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { if (isDirectCallable()) { return forwardPolicy.getExpiryForCreation(); } return getClient().invoke(new GetExpiryOperation(ExpiryPolicyServer.EntryOperation.CREATION)); }
Example #16
Source File: CacheTest.java From commons-jcs with Apache License 2.0 | 5 votes |
@Test public void accessExpiry() throws InterruptedException { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), Thread.currentThread().getContextClassLoader(), cachingProvider.getDefaultProperties()); final Cache<Integer, Integer> cache = cacheManager.createCache( "test", new MutableConfiguration<Integer, Integer>() .setStoreByValue(false) .setStatisticsEnabled(true) .setManagementEnabled(true) .setTypes(Integer.class, Integer.class) .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, 500)))); try { cache.put(1, 2); cache.get(1); Thread.sleep(650); assertFalse(cache.containsKey(1)); cache.put(1, 2); for (int i = 0; i < 3; i++) { // we update the last access to force the idle time and lastaccess to be synced Thread.sleep(250); assertTrue("iteration: " + Integer.toString(i), cache.containsKey(1)); } assertTrue(cache.containsKey(1)); Thread.sleep(650); assertFalse(cache.containsKey(1)); } finally { cacheManager.close(); cachingProvider.close(); } }
Example #17
Source File: GridCacheCommandHandler.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public IgniteInternalFuture<?> applyx(IgniteInternalCache<Object, Object> c, GridKernalContext ctx) { if (ttl != null && ttl > 0) { Duration duration = new Duration(MILLISECONDS, ttl); c = c.withExpiryPolicy(new ModifiedExpiryPolicy(duration)); } return c.putAsync(key, val); }
Example #18
Source File: ExpiryPolicyClient.java From cache2k with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public Duration onInvoke(ObjectInputStream ois, ObjectOutputStream oos) throws IOException, ClassNotFoundException { oos.writeObject(entryOperation.name()); Object o = ois.readObject(); if (o instanceof RuntimeException) { throw (RuntimeException) o; } else { return (Duration) o; } }
Example #19
Source File: IgniteCacheExpiryPolicyAbstractTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @throws Exception If failed. */ @Test public void testZeroOnCreate() throws Exception { factory = CreatedExpiryPolicy.factoryOf(Duration.ZERO); startGrids(); for (final Integer key : keys()) { log.info("Test zero duration on create, key: " + key); zeroOnCreate(key); } }
Example #20
Source File: CacheUtils.java From hazelcast-simulator with Apache License 2.0 | 5 votes |
public static void sleepDurationTwice(Logger logger, Duration duration) { if (duration.isEternal() || duration.isZero()) { return; } TimeUnit timeUnit = duration.getTimeUnit(); long timeout = duration.getDurationAmount() * 2; logger.info(format("Sleeping for %d %s...", timeout, timeUnit)); sleepTimeUnit(timeUnit, timeout); }
Example #21
Source File: Eh107XmlIntegrationTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void test107ExpiryOverriddenByEhcacheTemplateExpiry() { final AtomicBoolean expiryFactoryInvoked = new AtomicBoolean(false); MutableConfiguration<Long, Product> configuration = new MutableConfiguration<>(); configuration.setTypes(Long.class, Product.class); configuration.setExpiryPolicyFactory(() -> { expiryFactoryInvoked.set(true); return new CreatedExpiryPolicy(Duration.FIVE_MINUTES); }); cacheManager.createCache("productCache3", configuration); assertThat(expiryFactoryInvoked.get(), is(false)); }
Example #22
Source File: PlatformExpiryPolicy.java From ignite with Apache License 2.0 | 5 votes |
/** * Convert encoded duration to actual duration. * * @param dur Encoded duration. * @return Actual duration. */ private static Duration convert(long dur) { if (dur == DUR_UNCHANGED) return null; else if (dur == DUR_ETERNAL) return Duration.ETERNAL; else if (dur == DUR_ZERO) return Duration.ZERO; else { assert dur > 0; return new Duration(TimeUnit.MILLISECONDS, dur); } }
Example #23
Source File: ExpiryPolicyToEhcacheExpiry.java From ehcache3 with Apache License 2.0 | 5 votes |
@Override public java.time.Duration getExpiryForUpdate(K key, Supplier<? extends V> oldValue, V newValue) { try { Duration duration = expiryPolicy.getExpiryForUpdate(); if (duration == null) { return null; } return convertDuration(duration); } catch (Throwable t) { return java.time.Duration.ZERO; } }
Example #24
Source File: JCacheLoaderAdapter.java From caffeine with Apache License 2.0 | 5 votes |
private long expireTimeMS() { try { Duration duration = expiry.getExpiryForCreation(); if (duration.isZero()) { return 0; } else if (duration.isEternal()) { return Long.MAX_VALUE; } long millis = TimeUnit.NANOSECONDS.toMillis(ticker.read()); return duration.getAdjustedTime(millis); } catch (Exception e) { return Long.MAX_VALUE; } }
Example #25
Source File: IgnitePdsWithTtlDeactivateOnHighloadTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Returns a new cache configuration with the given name and {@code GROUP_NAME} group. * * @param name Cache name. * @return Cache configuration. */ private CacheConfiguration<?, ?> getCacheConfiguration(String name) { CacheConfiguration<?, ?> ccfg = new CacheConfiguration<>(); ccfg.setName(name); ccfg.setAffinity(new RendezvousAffinityFunction(false, PART_SIZE)); ccfg.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, EXPIRATION_TIMEOUT))); ccfg.setEagerTtl(true); ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); ccfg.setRebalanceMode(CacheRebalanceMode.SYNC); return ccfg; }
Example #26
Source File: GridCacheAbstractFullApiSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @throws Exception If failed. */ @Test public void testCompactExpired() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final String key = F.first(primaryKeysForCache(cache, 1)); cache.put(key, 1); long ttl = 500; final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); grid(0).cache(DEFAULT_CACHE_NAME).withExpiryPolicy(expiry).put(key, 1); waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return cache.localPeek(key) == null; } }, ttl + 1000); // Peek will actually remove entry from cache. assertNull(cache.localPeek(key)); assertEquals(0, cache.localSize()); // Clear readers, if any. cache.remove(key); }
Example #27
Source File: IgniteCacheEntryListenerExpiredEventsTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @param ccfg Cache configuration. * @throws Exception If failed. */ private void checkExpiredEvents(CacheConfiguration<Object, Object> ccfg) throws Exception { IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg); try { evtCntr = new AtomicInteger(); CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>( new ExpiredListenerFactory(), null, true, false ); cache.registerCacheEntryListener(lsnrCfg); IgniteCache<Object, Object> expiryCache = cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 500))); expiryCache.put(1, 1); for (int i = 0; i < 10; i++) cache.get(i); boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return evtCntr.get() > 0; } }, 5000); assertTrue(wait); U.sleep(100); assertEquals(1, evtCntr.get()); } finally { ignite(0).destroyCache(cache.getName()); } }
Example #28
Source File: DiagnosticLogForPartitionStatesTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Tests that partitions validation is not triggered when custom expiry policy is explicitly used. * * @throws Exception If failed. */ @Test public void shouldNotPrintMessageIfPartitionHasOtherCounterButHasCustomExpiryPolicy() throws Exception { doTest( new CacheConfiguration<Integer, Integer>(CACHE_1) .setBackups(1) .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1))), false ); }
Example #29
Source File: ExpiryPolicyServer.java From cache2k with Apache License 2.0 | 5 votes |
@Override public void onProcess(ObjectInputStream ois, ObjectOutputStream oos) throws IOException, ClassNotFoundException { if (expiryPolicy == null) { throw new NullPointerException("The ExpiryPolicy for the ExpiryPolicyServer has not be set"); } else { EntryOperation entryOperation = EntryOperation.valueOf((String)ois.readObject()); try { Duration duration; switch (entryOperation) { case CREATION: duration = expiryPolicy.getExpiryForCreation(); break; case ACCESSED: duration = expiryPolicy.getExpiryForAccess(); break; case UPDATED: duration = expiryPolicy.getExpiryForUpdate(); break; default: duration = null; break; } oos.writeObject(duration); } catch (Exception e) { oos.writeObject(e); } } }
Example #30
Source File: CacheUtils.java From hazelcast-simulator with Apache License 2.0 | 5 votes |
public static void sleepDurationTwice(Logger logger, Duration duration) { if (duration.isEternal() || duration.isZero()) { return; } TimeUnit timeUnit = duration.getTimeUnit(); long timeout = duration.getDurationAmount() * 2; logger.info(format("Sleeping for %d %s...", timeout, timeUnit)); sleepTimeUnit(timeUnit, timeout); }