Example usage for com.google.common.cache RemovalCause REPLACED

List of usage examples for com.google.common.cache RemovalCause REPLACED

Introduction

In this page you can find the example usage for com.google.common.cache RemovalCause REPLACED.

Prototype

RemovalCause REPLACED

To view the source code for com.google.common.cache RemovalCause REPLACED.

Click Source Link

Document

The entry itself was not actually removed, but its value was replaced by the user.

Usage

From source file:rapture.kernel.cache.KernelCaches.java

private static Cache<RaptureURI, Optional<String>> setupObjectStorageCache() {
    return CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES)
            .removalListener(new RemovalListener<RaptureURI, Optional<String>>() {
                @Override//  w ww.  j a  v  a2  s .co  m
                public void onRemoval(RemovalNotification<RaptureURI, Optional<String>> notification) {
                    if (notification.getCause() != RemovalCause.REPLACED) {
                        if (log.isTraceEnabled())
                            log.trace("Removed " + notification.getKey() + " from local cache because "
                                    + notification.getCause());
                    }
                }
            }).build();
}

From source file:com.codefollower.lealone.omid.tso.GuavaCache.java

@Override
public void onRemoval(RemovalNotification<Long, Long> notification) {
    if (notification.getCause() == RemovalCause.REPLACED) {
        return;// w  ww  .  j a v a2 s .c  om
    }
    //        LOG.warn("Removing " + notification);
    //        new Exception().printStackTrace();
    removed = Math.max(removed, notification.getValue());
}

From source file:ezbake.discovery.stethoscope.server.StethoscopeCacheRemovalListener.java

@Override
public void onRemoval(RemovalNotification<String, StethoscopeCacheEntry> entry) {
    if (entry.getCause() == RemovalCause.REPLACED) {
        // We don't want to do anything here since our key gets a new value
        return;/*from w  w w  .  j a  v  a 2  s .  c om*/
    }

    String appName = entry.getValue().getApplicationName();
    String serviceName = entry.getValue().getServiceName();
    if (servicesToIgnore.containsEntry(appName, serviceName)) {
        logger.info("Ignoring: {},{} and NOT removing that from zookeeper", appName, serviceName);
        return;
    }

    String endpoint = entry.getKey();

    // We want to ignore removing ourself for right now
    if (appName.equals(ServiceDiscoveryClient.COMMON_SERVICE_APP_NAME)
            && serviceName.equals(stethoscopeConstants.SERVICE_NAME)) {
        return;
    }

    if (!shouldRemoveEntriesFromZookeeper) {
        logger.info("Would have removed: {} for {} {} from zookeeper!", endpoint, appName, serviceName);
        return;
    }

    try {
        serviceDiscoveryClient.unregisterEndpoint(appName, serviceName, endpoint);
        logger.info("Removed: {} for {} {} from zookeeper!", endpoint, appName, serviceName);
    } catch (Exception e) {
        StringBuilder builder = new StringBuilder("We had an error removing /ezdiscovery/").append(appName)
                .append("/").append("/endpoints/").append(endpoint).append("from zookeeper!");

        logger.error(builder.toString(), e);
    }
}

From source file:io.pravega.shared.metrics.DynamicLoggerImpl.java

public DynamicLoggerImpl(MetricsConfig metricsConfig, MetricRegistry metrics, StatsLogger statsLogger) {
    Preconditions.checkNotNull(metricsConfig, "metricsConfig");
    Preconditions.checkNotNull(metrics, "metrics");
    Preconditions.checkNotNull(statsLogger, "statsLogger");
    this.metrics = metrics;
    this.underlying = statsLogger;
    this.cacheSize = metricsConfig.getDynamicCacheSize();

    countersCache = CacheBuilder.newBuilder().maximumSize(cacheSize)
            .removalListener(new RemovalListener<String, Counter>() {
                @Override//from   ww  w . j  av a 2  s.com
                public void onRemoval(RemovalNotification<String, Counter> removal) {
                    Counter counter = removal.getValue();
                    if (removal.getCause() != RemovalCause.REPLACED) {
                        Exceptions.checkNotNullOrEmpty(counter.getName(), "counter");
                        metrics.remove(counter.getName());
                        log.debug("Removed Counter: {}.", counter.getName());
                    }
                }
            }).build();

    gaugesCache = CacheBuilder.newBuilder().maximumSize(cacheSize)
            .removalListener(new RemovalListener<String, Gauge>() {
                @Override
                public void onRemoval(RemovalNotification<String, Gauge> removal) {
                    Gauge gauge = removal.getValue();
                    if (removal.getCause() != RemovalCause.REPLACED) {
                        Exceptions.checkNotNullOrEmpty(gauge.getName(), "gauge");
                        metrics.remove(gauge.getName());
                        log.debug("Removed Gauge: {}.", gauge.getName());
                    }
                }
            }).build();

    metersCache = CacheBuilder.newBuilder().maximumSize(cacheSize)
            .removalListener(new RemovalListener<String, Meter>() {
                @Override
                public void onRemoval(RemovalNotification<String, Meter> removal) {
                    Meter meter = removal.getValue();
                    if (removal.getCause() != RemovalCause.REPLACED) {
                        Exceptions.checkNotNullOrEmpty(meter.getName(), "meter");
                        metrics.remove(meter.getName());
                        log.debug("Removed Meter: {}.", meter.getName());
                    }
                }
            }).build();
}

From source file:org.janusgraph.graphdb.transaction.vertexcache.GuavaVertexCache.java

public GuavaVertexCache(final long maxCacheSize, final int concurrencyLevel, final int initialDirtySize) {
    volatileVertices = new NonBlockingHashMapLong<InternalVertex>(initialDirtySize);
    log.debug("Created dirty vertex map with initial size {}", initialDirtySize);

    cache = CacheBuilder.newBuilder().maximumSize(maxCacheSize).concurrencyLevel(concurrencyLevel)
            .removalListener(new RemovalListener<Long, InternalVertex>() {
                @Override//from  w  w w .j a  v a  2 s.  c o  m
                public void onRemoval(RemovalNotification<Long, InternalVertex> notification) {
                    if (notification.getCause() == RemovalCause.EXPLICIT) { //Due to invalidation at the end
                        assert volatileVertices.isEmpty();
                        return;
                    }
                    //Should only get evicted based on size constraint or replaced through add
                    assert (notification.getCause() == RemovalCause.SIZE
                            || notification.getCause() == RemovalCause.REPLACED) : "Cause: "
                                    + notification.getCause();
                    InternalVertex v = notification.getValue();
                    if (v.isModified()) {
                        volatileVertices.putIfAbsent(notification.getKey(), v);
                    }
                }
            }).build();
    log.debug("Created vertex cache with max size {}", maxCacheSize);
}

From source file:com.comphenix.protocol.concurrency.BlockingHashMap.java

/**
 * Initialize a new map.//from w  ww  .  jav  a2s .c  o  m
 */
public BlockingHashMap() {
    backingMap = SafeCacheBuilder.<TKey, TValue>newBuilder().weakValues()
            .removalListener(new RemovalListener<TKey, TValue>() {
                @Override
                public void onRemoval(RemovalNotification<TKey, TValue> entry) {
                    // Clean up locks too
                    if (entry.getCause() != RemovalCause.REPLACED) {
                        locks.remove(entry.getKey());
                    }
                }
            }).build(BlockingHashMap.<TKey, TValue>newInvalidCacheLoader());

    // Normal concurrent hash map
    locks = new ConcurrentHashMap<TKey, Object>();
}

From source file:com.google.cloud.dataflow.sdk.runners.worker.WindmillStateCache.java

public WindmillStateCache() {
    final Weigher<Weighted, Weighted> weigher = Weighers.weightedKeysAndValues();

    stateCache = CacheBuilder.newBuilder().maximumWeight(100000000 /* 100 MB */).recordStats().weigher(weigher)
            .removalListener(new RemovalListener<StateId, StateCacheEntry>() {
                @Override/*from   ww  w . j  av a2 s  .  c  o m*/
                public void onRemoval(RemovalNotification<StateId, StateCacheEntry> removal) {
                    if (removal.getCause() != RemovalCause.REPLACED) {
                        displayedWeight -= weigher.weigh(removal.getKey(), removal.getValue());
                    }
                }
            }).build();
}

From source file:org.apache.beam.runners.dataflow.worker.WindmillStateCache.java

public WindmillStateCache() {
    final Weigher<Weighted, Weighted> weigher = Weighers.weightedKeysAndValues();

    stateCache = CacheBuilder.newBuilder().maximumWeight(100000000 /* 100 MB */).recordStats().weigher(weigher)
            .removalListener(removal -> {
                if (removal.getCause() != RemovalCause.REPLACED) {
                    synchronized (this) {
                        StateId id = (StateId) removal.getKey();
                        if (removal.getCause() != RemovalCause.EXPLICIT) {
                            // When we invalidate a key explicitly, we'll also update the keyIndex, so
                            // no need to do it here.
                            keyIndex.remove(id.getComputationKey(), id);
                        }/*from w ww.j a va 2 s  . c  o m*/
                        displayedWeight -= weigher.weigh(id, removal.getValue());
                    }
                }
            }).build();
}

From source file:org.waveprotocol.box.server.contact.ContactManagerImpl.java

@Inject
public ContactManagerImpl(final ContactStore contactStore,
        @ExecutorAnnotations.ContactExecutor ScheduledExecutorService executor) {
    contactsCache = CacheBuilder.newBuilder().maximumSize(READ_CACHE_MAX_SIZE)
            .build(new CacheLoader<ParticipantId, Map<ParticipantId, Contact>>() {
                @Override//from   w  w w  .j ava  2s.  c o m
                public Map<ParticipantId, Contact> load(ParticipantId participantId) throws Exception {
                    Map<ParticipantId, Contact> contacts = Maps.newHashMap();
                    List<Contact> list = contactStore.getContacts(participantId);
                    if (list != null) {
                        for (Contact contact : list) {
                            contacts.put(contact.getParticipantId(), contact);
                        }
                    }
                    return contacts;
                }
            });

    contactsToWrite = CacheBuilder.newBuilder().expireAfterWrite(WRITE_DELAY_SEC, TimeUnit.SECONDS)
            .removalListener(new RemovalListener<ParticipantId, Map<ParticipantId, Contact>>() {

                @Override
                public void onRemoval(RemovalNotification<ParticipantId, Map<ParticipantId, Contact>> notify) {
                    try {
                        if (notify.getCause() != RemovalCause.REPLACED) {
                            List<Contact> contacts = Lists.newArrayList();
                            for (Contact contact : notify.getValue().values()) {
                                contacts.add(contact);
                            }
                            contactStore.storeContacts(notify.getKey(), contacts);
                        }
                    } catch (PersistenceException ex) {
                        LOG.severe("Store contacts error", ex);
                    }
                }
            }).build();

    Runnable task = new Runnable() {

        @Override
        public void run() {
            contactsToWrite.cleanUp();
        }
    };
    executor.scheduleAtFixedRate(task, WRITE_DELAY_SEC, WRITE_DELAY_SEC, TimeUnit.SECONDS);
}

From source file:com.ning.metrics.collector.processing.db.InMemoryCounterCacheProcessor.java

@Inject
public InMemoryCounterCacheProcessor(final CollectorConfig config, final CounterStorage counterStorage) {

    this.executorShutdownTimeOut = config.getSpoolWriterExecutorShutdownTime();
    this.counterEventDBFlushTime = config.getCounterEventMemoryFlushTime();

    this.executorService = new LoggingExecutor(1, 1, Long.MAX_VALUE, TimeUnit.DAYS,
            new ArrayBlockingQueue<Runnable>(2), new NamedThreadFactory("CounterEvents-Storage-Threads"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    this.counterEventsBySubscriptionId = CacheBuilder.newBuilder()
            .expireAfterAccess(counterEventDBFlushTime.getPeriod(), counterEventDBFlushTime.getUnit())
            .maximumWeight(config.getMaxCounterEventFlushCacheCount())
            .weigher(new Weigher<String, Queue<CounterEventData>>() {
                @Override/*  w  w w. ja  v  a 2s . c o  m*/
                public int weigh(String key, Queue<CounterEventData> value) {
                    return value.size();
                }
            }).removalListener(
                    RemovalListeners.asynchronous(new RemovalListener<String, Queue<CounterEventData>>() {

                        @Override
                        public void onRemoval(
                                RemovalNotification<String, Queue<CounterEventData>> removalNotification) {
                            if (!Objects.equal(removalNotification.getCause(), RemovalCause.REPLACED)
                                    && !Objects.equal(null, removalNotification.getValue())
                                    && !removalNotification.getValue().isEmpty()) {
                                Multimap<String, CounterEventData> multimap = ArrayListMultimap.create();
                                List<CounterEventData> counterEventDataList = Lists
                                        .newArrayList(removalNotification.getValue());
                                removalNotification.getValue().clear();
                                Map<String, CounterEventData> groupMap = new ConcurrentHashMap<String, CounterEventData>();

                                for (CounterEventData counterEventData : counterEventDataList) {
                                    CounterEventData groupedData = groupMap
                                            .get(counterEventData.getUniqueIdentifier()
                                                    + counterEventData.getFormattedDate());

                                    if (Objects.equal(null, groupedData)) {
                                        groupMap.put(
                                                counterEventData.getUniqueIdentifier()
                                                        + counterEventData.getFormattedDate(),
                                                counterEventData);
                                        continue;
                                    }

                                    groupedData.mergeCounters(counterEventData.getCounters());
                                    groupMap.put(counterEventData.getUniqueIdentifier()
                                            + counterEventData.getFormattedDate(), groupedData);
                                }

                                multimap.putAll(removalNotification.getKey(), groupMap.values());
                                counterStorage.bufferMetrics(multimap);
                            }
                        }
                    }, this.executorService))
            .recordStats().build();

}