public <T> T get(String key, Supplier<T> compute) { Element element = ehcache.get(key); if (element != null) { return (T) element.getObjectValue(); } synchronized (key.intern()) { element = ehcache.get(key); if (element != null) { return (T) element.getObjectValue(); } T object = compute.get(); ehcache.put(new Element(key, object)); return object; } }
@Override public void evict(Object key) { this.cache.remove(key); }
/** * Removes all elements in the cache, but leaves the cache in a useable state. */ public void clear() throws CacheException { if (log.isTraceEnabled()) { log.trace("Clearing all objects from cache [" + cache.getName() + "]"); } try { cache.removeAll(); } catch (Throwable t) { throw new CacheException(t); } }
logger.debug("Using default EhCache CacheManager for cache region '" + cacheName + "'"); this.cacheManager = CacheManager.getInstance(); boolean cacheExists = this.cacheManager.cacheExists(cacheName); logger.debug("Using existing EhCache cache region '" + cacheName + "'"); rawCache = this.cacheManager.getEhcache(cacheName); rawCache.setBootstrapCacheLoader(this.bootstrapCacheLoader); rawCache.getCacheEventNotificationService().registerListener(listener); rawCache.setDisabled(true);
/** * {@inheritDoc} */ public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { try { if (minimalPutOverride && ehcache.get(key) != null) { return false; } //OptimisticCache? versioning? ehcache.put(new Element(key, value)); return true; } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
@Override public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) { try { final Element element = new Element( key, value ); getCache().put( element ); } catch (IllegalArgumentException | IllegalStateException e) { throw new CacheException( e ); } catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); } else { throw new CacheException( e ); } } }
private void initSupportCache() { this.supportConfig = new CacheConfiguration(); supportConfig.name(underlyingCache.getName() + "_" + getClass().getName() + "_refreshAheadSupport"); supportConfig = supportConfig.persistence(new PersistenceConfiguration().strategy(Strategy.NONE)); int activeSize = 2 * refreshAheadConfig.getBatchSize() * refreshAheadConfig.getNumberOfThreads(); supportConfig = supportConfig.maxEntriesLocalHeap(activeSize); if (underlyingCache.getCacheConfiguration().isTerracottaClustered()) { supportConfig = supportConfig.persistence(new PersistenceConfiguration().strategy(Strategy.DISTRIBUTED)); this.supportCache = new Cache(supportConfig); Ehcache prior = underlyingCache.getCacheManager().addCacheIfAbsent(supportCache); if (prior != supportCache) { throw new IllegalStateException("Unable to add refresh ahead support cache due to name collision: " prior.removeAll(); underlyingCache.registerCacheExtension(new CacheExtension() {
@Override public Object getFromCache(Object key, SharedSessionContractImplementor session) { try { final Element element = getCache().get( key ); if ( element == null ) { return null; } else { return element.getObjectValue(); } } catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); return null; } else { throw new CacheException( e ); } } }
@Test public void testEhCacheFactoryBeanWithSelfPopulatingCache() { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); EhCacheFactoryBean cacheFb = new EhCacheFactoryBean(); cacheFb.setCacheManager(cm); cacheFb.setCacheName("myCache1"); cacheFb.setCacheEntryFactory(key -> key); assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); assertTrue(myCache1 instanceof SelfPopulatingCache); assertEquals("myKey1", myCache1.get("myKey1").getObjectValue()); } finally { cacheManagerFb.destroy(); } }
/** * Loads an existing EhCache from the cache manager, or starts a new cache if one is not found. * * @param name the name of the cache to load/create. */ public final <K, V> Cache<K, V> getCache(String name) throws CacheException { if (log.isTraceEnabled()) { log.trace("Acquiring EhCache instance named [" + name + "]"); } try { net.sf.ehcache.Ehcache cache = ensureCacheManager().getEhcache(name); if (cache == null) { if (log.isInfoEnabled()) { log.info("Cache with name '{}' does not yet exist. Creating now.", name); } this.manager.addCache(name); cache = manager.getCache(name); if (log.isInfoEnabled()) { log.info("Added EhCache named [" + name + "]"); } } else { if (log.isInfoEnabled()) { log.info("Using existing EHCache named [" + cache.getName() + "]"); } } return new EhCache<K, V>(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
buf.append("\n\n"); String[] allCacheNames = cacheManager.getCacheNames(); Arrays.sort(allCacheNames); ArrayList<Ehcache> caches = new ArrayList<Ehcache>(allCacheNames.length); for (String cacheName : allCacheNames) { Ehcache cache = cacheManager.getCache(cacheName); caches.add(cache); buf.append(cache.toString()); buf.append("\n"); long maxEntries = cache.getCacheConfiguration().getMaxEntriesLocalHeap(); long ttlSecs = cache.getCacheConfiguration().getTimeToLiveSeconds(); long ttiSecs = cache.getCacheConfiguration().getTimeToIdleSeconds(); boolean eternal = cache.getCacheConfiguration().isEternal(); if (maxEntries == maxEntriesDefault && ttlSecs == ttlSecsDefault && ttiSecs == ttiSecsDefault && eternal == eternalDefault) { buf.append("# memory.").append(cache.getName()).append(" *ALL DEFAULTS*\n"); } else { buf.append("memory.").append(cache.getName()).append("="); boolean first = true; if (maxEntries != maxEntriesDefault) { if (cache.getCacheConfiguration().isOverflowToDisk()) { buf.append("# NOTE: ").append(cache.getName()).append(" is configured for Overflow(disk), ").append(cache.getCacheConfiguration().getMaxEntriesLocalDisk()).append(" entries\n");
@Test public void testExpiredElements() throws Exception { Assume.group(TestGroup.LONG_RUNNING); String key = "brancusi"; String value = "constantin"; Element brancusi = new Element(key, value); // ttl = 10s brancusi.setTimeToLive(3); nativeCache.put(brancusi); assertEquals(value, cache.get(key).get()); // wait for the entry to expire Thread.sleep(5 * 1000); assertNull(cache.get(key)); }
private void doLoad(final Ehcache cache) { CacheManager manager = cache.getCacheManager(); if (manager == null) { throw new CacheException("Cache must belong to a cache manager to bootstrap"); } DiskStorePathManager pathManager = diskStorePathManager != null ? diskStorePathManager : cache.getCacheManager() .getDiskStorePathManager(); final RotatingSnapshotFile snapshotFile = new RotatingSnapshotFile(pathManager, cache.getName(), manager.getConfiguration().getClassLoader()); try { final Set<Object> keys = snapshotFile.readAll(); int loaded = 0; for (Object key : keys) { if (isInMemoryLimitReached(cache, loaded)) { break; } cache.get(key); loaded++; } LOG.info("Finished loading {} keys (of {} on disk) from previous snapshot for Cache '{}'", new Object[] {Integer.valueOf(loaded), keys.size(), cache.getName()}); } catch (IOException e) { LOG.error("Couldn't load keySet for Cache '{}'", cache.getName(), e); } if (doKeySnapshot) { keySnapshotter = new KeySnapshotter(cache, interval, doKeySnapshotOnDedicatedThread, snapshotFile); } }
@Override @SuppressWarnings("unchecked") @Nullable public <T> T get(Object key, @Nullable Class<T> type) { Element element = this.cache.get(key); Object value = (element != null ? element.getObjectValue() : null); if (value != null && type != null && !type.isInstance(value)) { throw new IllegalStateException( "Cached value is not of required type [" + type.getName() + "]: " + value); } return (T) value; }
@Test public void putInCache() throws Exception { myCache.putInCache(acl); verify(cache, times(2)).put(element.capture()); assertThat(element.getValue().getKey()).isEqualTo(acl.getId()); assertThat(element.getValue().getObjectValue()).isEqualTo(acl); assertThat(element.getAllValues().get(0).getKey()).isEqualTo( acl.getObjectIdentity()); assertThat(element.getAllValues().get(0).getObjectValue()).isEqualTo(acl); }