javax.cache.expiry.ExpiryPolicy Java Examples

The following examples show how to use javax.cache.expiry.ExpiryPolicy. 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: IgniteCacheExpiryPolicyAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testEternal() throws Exception {
    factory = EternalExpiryPolicy.factoryOf();

    ExpiryPolicy plc = factory.create();

    assertTrue(plc.getExpiryForCreation().isEternal());
    assertNull(plc.getExpiryForUpdate());
    assertNull(plc.getExpiryForAccess());

    startGrids();

    for (final Integer key : keys()) {
        log.info("Test eternalPolicy, key: " + key);

        eternal(key);
    }
}
 
Example #2
Source File: CacheHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public static <K, V> MutableConfiguration<K, V> createCacheConfig(
    @Nullable final Class<K> keyType,
    @Nullable final Class<V> valueType,
    final Factory<? extends ExpiryPolicy> expiryPolicyFactory)
{
  MutableConfiguration<K, V> config = new MutableConfiguration<K, V>()
      .setStoreByValue(false)
      .setExpiryPolicyFactory(expiryPolicyFactory)
      .setManagementEnabled(true)
      .setStatisticsEnabled(true);

  if (keyType != null && valueType != null) {
    config.setTypes(keyType, valueType);
  }
  return config;
}
 
Example #3
Source File: IgniteCacheExpiryPolicyWithStoreAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public ExpiryPolicy create() {
    return new ExpiryPolicy() {
        @Override public Duration getExpiryForCreation() {
            return new Duration(TimeUnit.MILLISECONDS, 500);
        }

        @Override public Duration getExpiryForAccess() {
            return new Duration(TimeUnit.MILLISECONDS, 600);
        }

        @Override public Duration getExpiryForUpdate() {
            return new Duration(TimeUnit.MILLISECONDS, 700);
        }
    };
}
 
Example #4
Source File: PlatformConfigurationUtils.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the policy factory.
 *
 * @param out Writer.
 */
public static void writeExpiryPolicyFactory(BinaryRawWriter out, Factory<? extends ExpiryPolicy> factory) {
    if (!(factory instanceof PlatformExpiryPolicyFactory)) {
        out.writeBoolean(false);

        return;
    }

    out.writeBoolean(true);

    PlatformExpiryPolicyFactory f = (PlatformExpiryPolicyFactory)factory;

    out.writeLong(f.getCreate());
    out.writeLong(f.getUpdate());
    out.writeLong(f.getAccess());
}
 
Example #5
Source File: CacheOperationContext.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param skipStore Skip store flag.
 * @param subjId Subject ID.
 * @param keepBinary Keep binary flag.
 * @param expiryPlc Expiry policy.
 * @param dataCenterId Data center id.
 * @param readRepair Read-repair flag.
 */
public CacheOperationContext(
    boolean skipStore,
    @Nullable UUID subjId,
    boolean keepBinary,
    @Nullable ExpiryPolicy expiryPlc,
    boolean noRetries,
    @Nullable Byte dataCenterId,
    boolean recovery,
    boolean readRepair,
    boolean allowAtomicOpsInTx
) {
    this.skipStore = skipStore;
    this.subjId = subjId;
    this.keepBinary = keepBinary;
    this.expiryPlc = expiryPlc;
    this.noRetries = noRetries;
    this.dataCenterId = dataCenterId;
    this.recovery = recovery;
    this.readRepair = readRepair;
    this.allowAtomicOpsInTx = allowAtomicOpsInTx;
}
 
Example #6
Source File: GridNearTxLocal.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected IgniteCacheExpiryPolicy accessPolicy(
    GridCacheContext ctx,
    IgniteTxKey key,
    @Nullable ExpiryPolicy expiryPlc
) {
    assert optimistic();

    IgniteCacheExpiryPolicy plc = ctx.cache().expiryPolicy(expiryPlc);

    if (plc != null) {
        if (accessMap == null)
            accessMap = new HashMap<>();

        accessMap.put(key, plc);
    }

    return plc;
}
 
Example #7
Source File: GridCacheTestEntryEx.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public GridTuple3<Boolean, Object, EntryProcessorResult<Object>> innerUpdateLocal(
    GridCacheVersion ver,
    GridCacheOperation op,
    @Nullable Object writeObj,
    @Nullable Object[] invokeArgs,
    boolean writeThrough,
    boolean readThrough,
    boolean retval,
    boolean keepBinary,
    @Nullable ExpiryPolicy expiryPlc,
    boolean evt,
    boolean metrics,
    @Nullable CacheEntryPredicate[] filter,
    boolean intercept,
    UUID subjId,
    String taskName,
    boolean transformOp)
    throws IgniteCheckedException, GridCacheEntryRemovedException {
    return new GridTuple3<>(false, null, null);
}
 
Example #8
Source File: IgniteCacheReadThroughEvictionSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@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 #9
Source File: GridCacheTtlManagerNotificationTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void run() {
    try {
        barrier.await();

        ExpiryPolicy plc1 = new CreatedExpiryPolicy(new Duration(MILLISECONDS, expirationDuration));

        int keyStart = keysRangeGenerator.getAndIncrement() * cnt;

        for (int i = keyStart; i < keyStart + cnt; i++)
            cache.withExpiryPolicy(plc1).put("key" + i, 1);

        barrier.await();
    }
    catch (Exception e) {
        throw new IgniteException(e);
    }
}
 
Example #10
Source File: GridDhtCacheAdapter.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void localLoad(Collection<? extends K> keys, final ExpiryPolicy plc, final boolean keepBinary)
    throws IgniteCheckedException {
    if (ctx.store().isLocal()) {
        super.localLoad(keys, plc, keepBinary);

        return;
    }

    // Version for all loaded entries.
    final AffinityTopologyVersion topVer = ctx.affinity().affinityTopologyVersion();

    final GridCacheVersion ver0 = ctx.shared().versions().nextForLoad(topVer);

    final boolean replicate = ctx.isDrEnabled();

    final ExpiryPolicy plc0 = plc != null ? plc : ctx.expiry();

    Collection<KeyCacheObject> keys0 = ctx.cacheKeysView(keys);

    ctx.store().loadAll(null, keys0, new CI2<KeyCacheObject, Object>() {
        @Override public void apply(KeyCacheObject key, Object val) {
            loadEntry(key, val, ver0, null, topVer, replicate, plc0);
        }
    });
}
 
Example #11
Source File: GridCacheProxyImpl.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public GridCacheProxyImpl<K, V> withExpiryPolicy(ExpiryPolicy plc) {
    CacheOperationContext prev = gate.enter(opCtx);

    try {
        return new GridCacheProxyImpl<>(ctx, delegate,
            opCtx != null ? opCtx.withExpiryPolicy(plc) :
                new CacheOperationContext(
                    false,
                    null,
                    false,
                    plc,
                    false,
                    null,
                    false,
                    false,
                    DFLT_ALLOW_ATOMIC_OPS_IN_TX));
    }
    finally {
        gate.leave(prev);
    }
}
 
Example #12
Source File: JmhWaitStategyBenchmark.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** @param rate duration will decrease with */
private static Factory<ExpiryPolicy> getExpiryPolicyFactoryWithDecreasingRate(final double rate) {
    return new Factory<ExpiryPolicy>() {
        @Override public ExpiryPolicy create() {
            return new RandomExpiryPolicy(rate);
        }
    };
}
 
Example #13
Source File: WebSessionFilter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param maxInactiveInteval Interval to use in expiry policy.
 * @param cache Cache.
 * @param <T> Cached object type.
 * @return Cache with expiry policy if {@code maxInactiveInteval} greater than zero.
 */
private <T> IgniteCache<String, T> cacheWithExpiryPolicy(final int maxInactiveInteval,
    final IgniteCache<String, T> cache) {
    if (maxInactiveInteval > 0) {
        long ttl = maxInactiveInteval * 1000L;

        ExpiryPolicy plc = new ModifiedExpiryPolicy(new Duration(MILLISECONDS, ttl));

        return cache.withExpiryPolicy(plc);
    }

    return cache;
}
 
Example #14
Source File: IgniteRepositoryImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <S extends V> Iterable<S> save(Map<K, S> entities, @Nullable ExpiryPolicy expiryPlc) {
    if (expiryPlc != null)
        cache.withExpiryPolicy(expiryPlc).putAll(entities);
    else
        cache.putAll(entities);
    return entities.values();
}
 
Example #15
Source File: IgniteRepositoryImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <S extends V> S save(K key, S entity, @Nullable ExpiryPolicy expiryPlc) {
    if (expiryPlc != null)
        cache.withExpiryPolicy(expiryPlc).put(key, entity);
    else
        cache.put(key, entity);
    return entity;
}
 
Example #16
Source File: PlatformConfigurationUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the expiry policy factory.
 *
 * @param in Reader.
 * @return Expiry policy factory.
 */
public static Factory<? extends ExpiryPolicy> readExpiryPolicyFactory(BinaryRawReader in) {
    if (!in.readBoolean())
        return null;

    return new PlatformExpiryPolicyFactory(in.readLong(), in.readLong(), in.readLong());
}
 
Example #17
Source File: Builder.java    From triava with Apache License 2.0 5 votes vote down vote up
@Override
public Builder<K,V> setMaxIdleTime(int maxIdleTime, TimeUnit timeUnit)
{
	if (maxIdleTime <= 0)
		throw new IllegalArgumentException("Invalid maxIdleTime: " + maxIdleTime);
	
	TouchedExpiryPolicy ep = new TouchedExpiryPolicy(new Duration(timeUnit, maxIdleTime));
	SingletonFactory<ExpiryPolicy> singletonFactory = new FactoryBuilder.SingletonFactory<ExpiryPolicy>(ep);
	this.expiryPolicyFactory = (Factory<ExpiryPolicy>)singletonFactory;
	
	return this;
}
 
Example #18
Source File: GatewayProtectedCacheProxy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public GatewayProtectedCacheProxy<K, V> withExpiryPolicy(ExpiryPolicy plc) {
    CacheOperationGate opGate = onEnter();

    try {
        MvccUtils.verifyMvccOperationSupport(delegate.context(), "withExpiryPolicy");

        return new GatewayProtectedCacheProxy<>(delegate, opCtx.withExpiryPolicy(plc), lock);
    }
    finally {
        onLeave(opGate);
    }
}
 
Example #19
Source File: GridLocalAtomicCache.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Entry point for public API remove methods.
 *
 * @param keys Keys to remove.
 * @param retval Return value required flag.
 * @param rawRetval Return {@code GridCacheReturn} instance.
 * @param filter Cache entry filter.
 * @return Completion future.
 */
private IgniteInternalFuture removeAllAsync0(
    @Nullable final Collection<? extends K> keys,
    final boolean retval,
    final boolean rawRetval,
    @Nullable final CacheEntryPredicate filter
) {
    final boolean writeThrough = ctx.writeThrough();

    final boolean readThrough = ctx.readThrough();

    final ExpiryPolicy expiryPlc = expiryPerCall();

    CacheOperationContext opCtx = ctx.operationContextPerCall();

    final boolean keepBinary = opCtx != null && opCtx.isKeepBinary();

    return asyncOp(new Callable<Object>() {
        @Override public Object call() throws Exception {
            return updateAllInternal(DELETE,
                keys,
                null,
                null,
                expiryPlc,
                retval,
                rawRetval,
                filter,
                writeThrough,
                readThrough,
                keepBinary);
        }
    });
}
 
Example #20
Source File: GridLocalAtomicCache.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @return Expiry policy.
 */
@Nullable private ExpiryPolicy expiryPerCall() {
    CacheOperationContext opCtx = ctx.operationContextPerCall();

    ExpiryPolicy expiry = opCtx != null ? opCtx.expiry() : null;

    if (expiry == null)
        expiry = ctx.expiry();

    return expiry;
}
 
Example #21
Source File: GridCacheUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Get TTL for load operation.
 *
 * @param plc Expiry policy.
 * @return TTL for load operation or {@link #TTL_ZERO} in case of immediate expiration.
 */
public static long ttlForLoad(ExpiryPolicy plc) {
    if (plc != null) {
        long ttl = toTtl(plc.getExpiryForCreation());

        if (ttl == TTL_NOT_CHANGED)
            ttl = TTL_ETERNAL;

        return ttl;
    }
    else
        return TTL_ETERNAL;
}
 
Example #22
Source File: IgniteTxLocalAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ctx Cache context.
 * @param key Key.
 * @param expiryPlc Expiry policy.
 * @return Expiry policy wrapper for entries accessed locally in optimistic transaction.
 */
protected IgniteCacheExpiryPolicy accessPolicy(
    GridCacheContext ctx,
    IgniteTxKey key,
    @Nullable ExpiryPolicy expiryPlc
) {
    return null;
}
 
Example #23
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #24
Source File: GridNearCacheAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param tx Transaction.
 * @param keys Keys to load.
 * @param forcePrimary Force primary flag.
 * @param subjId Subject ID.
 * @param taskName Task name.
 * @param deserializeBinary Deserialize binary flag.
 * @param expiryPlc Expiry policy.
 * @param skipVal Skip value flag.
 * @param skipStore Skip store flag.
 * @param needVer Need version.
 * @return Loaded values.
 */
public IgniteInternalFuture<Map<K, V>> loadAsync(
    @Nullable IgniteInternalTx tx,
    @Nullable Collection<KeyCacheObject> keys,
    boolean forcePrimary,
    @Nullable UUID subjId,
    String taskName,
    boolean deserializeBinary,
    boolean recovery,
    @Nullable ExpiryPolicy expiryPlc,
    boolean skipVal,
    boolean skipStore,
    boolean needVer
) {
    if (F.isEmpty(keys))
        return new GridFinishedFuture<>(Collections.<K, V>emptyMap());

    IgniteTxLocalEx txx = (tx != null && tx.local()) ? (IgniteTxLocalEx)tx : null;

    final IgniteCacheExpiryPolicy expiry = expiryPolicy(expiryPlc);

    GridNearGetFuture<K, V> fut = new GridNearGetFuture<>(ctx,
        keys,
        !skipStore,
        forcePrimary,
        txx,
        subjId,
        taskName,
        deserializeBinary,
        expiry,
        skipVal,
        needVer,
        false,
        recovery);

    // init() will register future for responses if future has remote mappings.
    fut.init(null);

    return fut;
}
 
Example #25
Source File: GridNearAtomicFullUpdateRequest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param cacheId Cache ID.
 * @param nodeId Node ID.
 * @param futId Future ID.
 * @param topVer Topology version.
 * @param syncMode Synchronization mode.
 * @param op Cache update operation.
 * @param expiryPlc Expiry policy.
 * @param invokeArgs Optional arguments for entry processor.
 * @param filter Optional filter for atomic check.
 * @param subjId Subject ID.
 * @param taskNameHash Task name hash code.
 * @param flags Flags.
 * @param addDepInfo Deployment info flag.
 * @param maxEntryCnt Maximum entries count.
 */
GridNearAtomicFullUpdateRequest(
    int cacheId,
    UUID nodeId,
    long futId,
    @NotNull AffinityTopologyVersion topVer,
    CacheWriteSynchronizationMode syncMode,
    GridCacheOperation op,
    @Nullable ExpiryPolicy expiryPlc,
    @Nullable Object[] invokeArgs,
    @Nullable CacheEntryPredicate[] filter,
    @Nullable UUID subjId,
    int taskNameHash,
    byte flags,
    boolean addDepInfo,
    int maxEntryCnt
) {
    super(cacheId,
        nodeId,
        futId,
        topVer,
        syncMode,
        op,
        subjId,
        taskNameHash,
        flags,
        addDepInfo);

    this.expiryPlc = expiryPlc;
    this.invokeArgs = invokeArgs;
    this.filter = filter;

    // By default ArrayList expands to array of 10 elements on first add. We cannot guess how many entries
    // will be added to request because of unknown affinity distribution. However, we DO KNOW how many keys
    // participate in request. As such, we know upper bound of all collections in request. If this bound is lower
    // than 10, we use it.
    initSize = Math.min(maxEntryCnt, 10);

    keys = new ArrayList<>(initSize);
}
 
Example #26
Source File: TcpClientCache.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Constructor. */
TcpClientCache(String name, ReliableChannel ch, ClientBinaryMarshaller marsh, TcpClientTransactions transactions,
    boolean keepBinary, ExpiryPolicy expiryPlc) {
    this.name = name;
    this.cacheId = ClientUtils.cacheId(name);
    this.ch = ch;
    this.marsh = marsh;
    this.transactions = transactions;

    serDes = new ClientUtils(marsh);

    this.keepBinary = keepBinary;
    this.expiryPlc = expiryPlc;
}
 
Example #27
Source File: IgniteCacheProcessProxy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param name Name.
 * @param async Async flag.
 * @param plc Expiry policy.
 * @param proxy Ignite Process Proxy.
 */
private IgniteCacheProcessProxy(String name, boolean async, ExpiryPolicy plc, IgniteProcessProxy proxy) {
    cacheName = name;
    isAsync = async;
    expiryPlc = plc;
    igniteProxy = proxy;
    compute = proxy.remoteCompute();
}
 
Example #28
Source File: CacheHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public synchronized <K, V> Cache<K, V> maybeCreateCache(final String name,
                                                        @Nullable final Class<K> keyType,
                                                        @Nullable final Class<V> valueType,
                                                        final Factory<? extends ExpiryPolicy> expiryPolicyFactory)
{
  return maybeCreateCache(name, createCacheConfig(keyType, valueType, expiryPolicyFactory));
}
 
Example #29
Source File: JCacheStore.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
public JCacheStore(Factory<ExpiryPolicy> expiryPolicyFactory) {
    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();

    MutableConfiguration<String, Serializable> config = new MutableConfiguration<String, Serializable>()
            .setTypes(String.class, Serializable.class);
    if (expiryPolicyFactory != null) {
        config.setExpiryPolicyFactory(expiryPolicyFactory);
    }
    cache = cacheManager.getCache("session", String.class, Serializable.class);
    if (cache == null)
        cache = cacheManager.createCache("session", config);
}
 
Example #30
Source File: IgniteTxLocalAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param key Key.
 * @param expiryPlc Expiry policy.
 */
void entryExpiry(IgniteTxKey key, @Nullable ExpiryPolicy expiryPlc) {
    assert key != null;

    IgniteTxEntry e = entry(key);

    if (e != null) {
        e.expiry(expiryPlc);
        e.conflictExpireTime(CU.EXPIRE_TIME_CALCULATE);
    }
}