Java Code Examples for com.google.common.cache.CacheBuilder#removalListener()

The following examples show how to use com.google.common.cache.CacheBuilder#removalListener() . 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: NetflowV9Decoder.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static Cache<FlowSetTemplateCacheKey, FlowSetTemplate> buildTemplateCache(
    int maxTemplateCacheSize,
    int templateCacheTimeoutMs
) {
  CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
  if (maxTemplateCacheSize > 0) {
    cacheBuilder = cacheBuilder.maximumSize(maxTemplateCacheSize);
  }
  if (templateCacheTimeoutMs > 0) {
    cacheBuilder = cacheBuilder.expireAfterAccess(templateCacheTimeoutMs, TimeUnit.MILLISECONDS);
  }
  if (LOG.isTraceEnabled()) {
    cacheBuilder = cacheBuilder.removalListener((notification) -> LOG.trace(
        "Removing flow set template entry {} for cause: {} ",
        notification.getKey(),
        notification.getCause()
    ));
  }
  return cacheBuilder.build();
}
 
Example 2
Source File: UsageTrackingCache.java    From docker-plugin with MIT License 6 votes vote down vote up
/**
 * Full constructor.
 * 
 * @param duration
 *            How long inactive things should be kept in the cache.
 * @param unit
 *            The <code>duration</code>'s unit of measurement.
 * @param expiryHandler
 *            Callback that is given all expired values from the cache just
 *            before they are thrown away.
 */
UsageTrackingCache(final long duration, @Nonnull final TimeUnit unit,
        @Nonnull final ExpiryHandler<K, V> expiryHandler) {
    activeCacheByKey = new HashMap<>();
    activeCacheByValue = new IdentityHashMap();
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder = cacheBuilder.expireAfterAccess(duration, unit);
    final RemovalListener removalHandler = new RemovalListener<K, CacheEntry<K, V>>() {
        @Override
        public void onRemoval(RemovalNotification<K, CacheEntry<K, V>> notification) {
            final K key = notification.getKey();
            if (!activeCacheByKey.containsKey(key)) {
                final CacheEntry<K, V> record = notification.getValue();
                final V value = record.getValue();
                expiryHandler.entryDroppedFromCache(key, value);
            }
        }
    };
    cacheBuilder = cacheBuilder.removalListener(removalHandler);
    durationCache = cacheBuilder.build();
}
 
Example 3
Source File: GuavaConcurrentMapFactory.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <K, V> ConcurrentMap<K, V> getMap(final ConcurrentMapListener<K, V> listener) {
	// Create cache builder
	CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();

	// Set expireAfterWrite
	if (expireDuration != null && expireUnit != null) {
		cacheBuilder = cacheBuilder.expireAfterWrite(expireDuration, expireUnit);
	}

	// Configure listener
	if (listener != null) {
		cacheBuilder.removalListener((RemovalListener<K, V>) notification -> {
			K key = notification.getKey();
			V value = notification.getValue();
			switch (notification.getCause()) {
				case REPLACED:
					listener.entryUpdated(key, value);
					break;
				case EXPLICIT:
					listener.entryRemoved(key, value);
					break;
				case COLLECTED:
				case EXPIRED:
				case SIZE:
					listener.entryEvicted(key, value);
					break;
			}
		});
	}

	// Build cache
	Cache<K, V> cache = cacheBuilder.build();

	return cache.asMap();
}
 
Example 4
Source File: LRUCache.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private LRUCache(final Function<Key, Value> loader, final RemovalListener<Key, Value> listener, final long maximumSize, final long expireDuration) {
    final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if(listener != null) {
        builder.removalListener(new RemovalListener<Key, Value>() {
            @Override
            public void onRemoval(final RemovalNotification<Key, Value> notification) {
                if(log.isDebugEnabled()) {
                    log.debug(String.format("Removed %s from cache with cause %s", notification.getKey(), notification.getCause()));
                }
                listener.onRemoval(notification);
            }
        });
    }
    if(maximumSize > 0) {
        builder.maximumSize(maximumSize);
    }
    if(expireDuration > 0) {
        builder.expireAfterAccess(expireDuration, TimeUnit.MILLISECONDS);
    }
    if(loader != null) {
        delegate = builder.build(new CacheLoader<Key, Value>() {
            @Override
            public Value load(Key key) {
                return loader.apply(key);
            }
        });
    }
    else {
        delegate = builder.build();
    }
}
 
Example 5
Source File: OstrichOwnerGroup.java    From emodb with Apache License 2.0 4 votes vote down vote up
public OstrichOwnerGroup(String group,
                         OstrichOwnerFactory<T> factory,
                         @Nullable Duration expireWhenInactive,
                         CuratorFramework curator,
                         HostDiscovery hostDiscovery,
                         HostAndPort self,
                         LeaderServiceTask dropwizardTask,
                         MetricRegistry metricRegistry) {
    _group = checkNotNull(group, "group");
    _factory = checkNotNull(factory, "factory");
    _curator = checkNotNull(curator, "curator");
    _hostDiscovery = checkNotNull(hostDiscovery, "hostDiscovery");
    _selfId = checkNotNull(self, "self").toString();
    _dropwizardTask = checkNotNull(dropwizardTask, "dropwizardTask");
    _expireWhenInactive = (expireWhenInactive != null);
    _metricRegistry = metricRegistry;

    // Build a cache of name -> leader service, used to track which objects this server is responsible for.
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (_expireWhenInactive) {
        cacheBuilder.expireAfterAccess(expireWhenInactive.toMillis(), TimeUnit.MILLISECONDS);
    }
    cacheBuilder.removalListener(new RemovalListener<String, Optional<LeaderService>>() {
        @Override
        public void onRemoval(RemovalNotification<String, Optional<LeaderService>> notification) {
            stopService(checkNotNull(notification.getKey()), checkNotNull(notification.getValue()));
        }
    });
    _leaderMap = cacheBuilder.build(new CacheLoader<String, Optional<LeaderService>>() {
        @Override
        public Optional<LeaderService> load(String name) throws Exception {
            return startService(name);
        }
    });

    // Watch for changes to the set of hosts since that affects which objects this server is responsible for.
    _endPointListener = new HostDiscovery.EndPointListener() {
        @Override
        public void onEndPointAdded(ServiceEndPoint endPoint) {
            onOwnersChanged();
        }

        @Override
        public void onEndPointRemoved(ServiceEndPoint endPoint) {
            onOwnersChanged();
        }
    };
    _hostDiscovery.addListener(_endPointListener);
}