Search in sources :

Example 6 with CacheEntry

use of org.cache2k.CacheEntry in project cache2k by cache2k.

the class ListenerTest method manyAsyncUpdateListenerCalled.

/**
 * Check that we do not miss events.
 */
@Test(timeout = TestingParameters.MAX_FINISH_WAIT_MILLIS)
public void manyAsyncUpdateListenerCalled() {
    final AtomicInteger _callCount = new AtomicInteger();
    final ConcurrentMap<Integer, Integer> _seenValues = new ConcurrentHashMap<Integer, Integer>();
    Cache<Integer, Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {

        @Override
        public void extend(final Cache2kBuilder<Integer, Integer> b) {
            b.addAsyncListener(new CacheEntryUpdatedListener<Integer, Integer>() {

                @Override
                public void onEntryUpdated(final Cache<Integer, Integer> cache, final CacheEntry<Integer, Integer> currentEntry, final CacheEntry<Integer, Integer> entryWithNewData) {
                    _seenValues.put(entryWithNewData.getValue(), entryWithNewData.getValue());
                    _callCount.incrementAndGet();
                }
            });
        }
    });
    c.put(1, 2);
    assertEquals(0, _callCount.get());
    final int _UPDATE_COUNT = 123;
    for (int i = 0; i < _UPDATE_COUNT; i++) {
        c.put(1, i);
    }
    ConcurrencyHelper.await(new Condition() {

        @Override
        public boolean check() throws Exception {
            return _callCount.get() == _UPDATE_COUNT;
        }
    });
    assertEquals("Event dispatching is using copied events", 123, _seenValues.size());
}
Also used : Condition(org.cache2k.test.util.Condition) IntCacheRule(org.cache2k.test.util.IntCacheRule) CacheRule(org.cache2k.test.util.CacheRule) CacheEntry(org.cache2k.CacheEntry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryUpdatedListener(org.cache2k.event.CacheEntryUpdatedListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Cache(org.cache2k.Cache) Test(org.junit.Test)

Example 7 with CacheEntry

use of org.cache2k.CacheEntry in project cache2k by cache2k.

the class ListenerTest method asyncUpdateListenerCalled.

/**
 * If the listener is not executed in separate thread, this would block
 */
@Test(timeout = TestingParameters.MAX_FINISH_WAIT_MILLIS)
public void asyncUpdateListenerCalled() {
    final AtomicInteger _callCount = new AtomicInteger();
    final CountDownLatch _fire = new CountDownLatch(1);
    Cache<Integer, Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {

        @Override
        public void extend(final Cache2kBuilder<Integer, Integer> b) {
            b.addAsyncListener(new CacheEntryUpdatedListener<Integer, Integer>() {

                @Override
                public void onEntryUpdated(final Cache<Integer, Integer> cache, final CacheEntry<Integer, Integer> currentEntry, final CacheEntry<Integer, Integer> entryWithNewData) {
                    try {
                        _fire.await();
                    } catch (InterruptedException ignore) {
                    }
                    _callCount.incrementAndGet();
                }
            });
        }
    });
    c.put(1, 2);
    assertEquals(0, _callCount.get());
    c.put(1, 2);
    assertEquals(0, _callCount.get());
    _fire.countDown();
    ConcurrencyHelper.await(new Condition() {

        @Override
        public boolean check() throws Exception {
            return _callCount.get() == 1;
        }
    });
}
Also used : Condition(org.cache2k.test.util.Condition) CountDownLatch(java.util.concurrent.CountDownLatch) IntCacheRule(org.cache2k.test.util.IntCacheRule) CacheRule(org.cache2k.test.util.CacheRule) CacheEntry(org.cache2k.CacheEntry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryUpdatedListener(org.cache2k.event.CacheEntryUpdatedListener) Cache(org.cache2k.Cache) Test(org.junit.Test)

Example 8 with CacheEntry

use of org.cache2k.CacheEntry in project cache2k by cache2k.

the class EntryAction method callListeners.

public void callListeners() {
    if (!mightHaveListeners()) {
        mutationReleaseLockAndStartTimer();
        return;
    }
    CacheEntry<K, V> _currentEntry = heapCache.returnEntry(entry);
    if (expiredImmediately) {
        if (storageDataValid || heapDataValid) {
            if (entryExpiredListeners() != null) {
                for (CacheEntryExpiredListener l : entryExpiredListeners()) {
                    try {
                        l.onEntryExpired(userCache, _currentEntry);
                    } catch (Throwable t) {
                        exceptionToPropagate = new ListenerException(t);
                    }
                }
            }
        }
    } else if (remove) {
        if (storageDataValid || heapDataValid) {
            if (entryRemovedListeners() != null) {
                for (CacheEntryRemovedListener l : entryRemovedListeners()) {
                    try {
                        l.onEntryRemoved(userCache, _currentEntry);
                    } catch (Throwable t) {
                        exceptionToPropagate = new ListenerException(t);
                    }
                }
            }
        }
    } else {
        if (storageDataValid || heapDataValid) {
            if (entryUpdatedListeners() != null) {
                CacheEntry<K, V> _previousEntry = heapCache.returnCacheEntry(entry.getKey(), oldValueOrException, previousModificationTime);
                for (CacheEntryUpdatedListener l : entryUpdatedListeners()) {
                    try {
                        l.onEntryUpdated(userCache, _previousEntry, _currentEntry);
                    } catch (Throwable t) {
                        exceptionToPropagate = new ListenerException(t);
                    }
                }
            }
        } else {
            if (entryCreatedListeners() != null) {
                for (CacheEntryCreatedListener l : entryCreatedListeners()) {
                    try {
                        l.onEntryCreated(userCache, _currentEntry);
                    } catch (Throwable t) {
                        exceptionToPropagate = new ListenerException(t);
                    }
                }
            }
        }
    }
    mutationReleaseLockAndStartTimer();
}
Also used : CacheEntryExpiredListener(org.cache2k.event.CacheEntryExpiredListener) CacheEntryUpdatedListener(org.cache2k.event.CacheEntryUpdatedListener) CacheEntryCreatedListener(org.cache2k.event.CacheEntryCreatedListener) CacheEntry(org.cache2k.CacheEntry) CacheEntryRemovedListener(org.cache2k.event.CacheEntryRemovedListener)

Example 9 with CacheEntry

use of org.cache2k.CacheEntry in project cache2k by cache2k.

the class JCacheBuilder method setupExpiryPolicy.

/**
 * Register a expiry policy to cache2k.
 *
 * <p>JSR107 requires that null values are deleted from the cache. We register an expiry policy
 * to cache2k to provide this behavior.
 */
private void setupExpiryPolicy() {
    if (cache2kConfiguration.getExpiryPolicy() != null) {
        org.cache2k.expiry.ExpiryPolicy<K, V> ep0;
        try {
            ep0 = cache2kConfiguration.getExpiryPolicy().supply(manager.getCache2kManager());
        } catch (Exception ex) {
            throw new CacheException("couldn't initialize expiry policy", ex);
        }
        final org.cache2k.expiry.ExpiryPolicy<K, V> ep = ep0;
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return ep.calculateExpiryTime(key, value, loadTime, oldEntry);
            }
        }));
        return;
    }
    if (config.getExpiryPolicyFactory() != null) {
        expiryPolicy = config.getExpiryPolicyFactory().create();
    }
    if (expiryPolicy == null || expiryPolicy instanceof EternalExpiryPolicy) {
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return ETERNAL;
            }
        }));
        return;
    }
    if (expiryPolicy instanceof ModifiedExpiryPolicy) {
        Duration d = expiryPolicy.getExpiryForCreation();
        final long _millisDuration = d.getTimeUnit().toMillis(d.getDurationAmount());
        if (_millisDuration == 0) {
            cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

                @Override
                public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                    return NO_CACHE;
                }
            }));
            return;
        }
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                return loadTime + _millisDuration;
            }
        }));
        return;
    }
    if (expiryPolicy instanceof CreatedExpiryPolicy) {
        cache2kConfiguration.setEternal(true);
        Duration d = expiryPolicy.getExpiryForCreation();
        final long _millisDuration = d.getTimeUnit().toMillis(d.getDurationAmount());
        if (_millisDuration == 0) {
            cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

                @Override
                public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                    return NO_CACHE;
                }
            }));
            return;
        }
        cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new org.cache2k.expiry.ExpiryPolicy<K, V>() {

            @Override
            public long calculateExpiryTime(final K key, final V value, final long loadTime, final CacheEntry<K, V> oldEntry) {
                if (value == null) {
                    return NO_CACHE;
                }
                if (oldEntry == null) {
                    return loadTime + _millisDuration;
                } else {
                    return NEUTRAL;
                }
            }
        }));
        return;
    }
    needsTouchyWrapper = true;
    cache2kConfiguration.setExpiryPolicy(new CustomizationReferenceSupplier<org.cache2k.expiry.ExpiryPolicy<K, V>>(new TouchyJCacheAdapter.ExpiryPolicyAdapter<K, V>(expiryPolicy)));
}
Also used : CacheException(javax.cache.CacheException) EternalExpiryPolicy(javax.cache.expiry.EternalExpiryPolicy) Duration(javax.cache.expiry.Duration) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) CacheEntry(org.cache2k.CacheEntry) CacheLoaderException(javax.cache.integration.CacheLoaderException) CacheException(javax.cache.CacheException) IOException(java.io.IOException) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) EternalExpiryPolicy(javax.cache.expiry.EternalExpiryPolicy) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy)

Example 10 with CacheEntry

use of org.cache2k.CacheEntry in project cache2k by cache2k.

the class OsgiIT method testEventPackage.

/**
 * Simple test to see whether event package is exported.
 */
@Test
public void testEventPackage() {
    CacheManager m = CacheManager.getInstance("testEventPackage");
    final AtomicInteger _count = new AtomicInteger();
    Cache<String, String> c = new Cache2kBuilder<String, String>() {
    }.manager(m).eternal(true).addListener(new CacheEntryCreatedListener<String, String>() {

        @Override
        public void onEntryCreated(final Cache<String, String> cache, final CacheEntry<String, String> entry) {
            _count.incrementAndGet();
        }
    }).build();
    c.put("abc", "123");
    assertTrue(c.containsKey("abc"));
    assertEquals("123", c.peek("abc"));
    assertEquals(1, _count.get());
    c.close();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryCreatedListener(org.cache2k.event.CacheEntryCreatedListener) CacheManager(org.cache2k.CacheManager) CacheEntry(org.cache2k.CacheEntry) Cache2kBuilder(org.cache2k.Cache2kBuilder) Cache(org.cache2k.Cache) Test(org.junit.Test)

Aggregations

CacheEntry (org.cache2k.CacheEntry)18 Test (org.junit.Test)16 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 CacheRule (org.cache2k.test.util.CacheRule)9 Cache (org.cache2k.Cache)8 Condition (org.cache2k.test.util.Condition)8 IntCacheRule (org.cache2k.test.util.IntCacheRule)8 ExpiryPolicy (org.cache2k.expiry.ExpiryPolicy)7 CacheEntryCreatedListener (org.cache2k.event.CacheEntryCreatedListener)4 CacheEntryUpdatedListener (org.cache2k.event.CacheEntryUpdatedListener)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 CacheEntryExpiredListener (org.cache2k.event.CacheEntryExpiredListener)2 CacheEntryRemovedListener (org.cache2k.event.CacheEntryRemovedListener)2 IOException (java.io.IOException)1 NoSuchElementException (java.util.NoSuchElementException)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 CacheException (javax.cache.CacheException)1 CreatedExpiryPolicy (javax.cache.expiry.CreatedExpiryPolicy)1 Duration (javax.cache.expiry.Duration)1