org.infinispan.cache.impl.SimpleCacheImpl Maven / Gradle / Ivy
package org.infinispan.cache.impl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.security.auth.Subject;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import org.infinispan.AdvancedCache;
import org.infinispan.CacheCollection;
import org.infinispan.CacheSet;
import org.infinispan.CacheStream;
import org.infinispan.LockedStream;
import org.infinispan.Version;
import org.infinispan.atomic.Delta;
import org.infinispan.batch.BatchContainer;
import org.infinispan.commons.api.BasicCacheContainer;
import org.infinispan.commons.dataconversion.Encoder;
import org.infinispan.commons.dataconversion.Wrapper;
import org.infinispan.commons.util.ByRef;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.CloseableIteratorCollectionAdapter;
import org.infinispan.commons.util.CloseableIteratorSetAdapter;
import org.infinispan.commons.util.CloseableSpliterator;
import org.infinispan.commons.util.Closeables;
import org.infinispan.commons.util.CollectionFactory;
import org.infinispan.commons.util.IteratorMapper;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.format.PropertyFormatter;
import org.infinispan.container.DataContainer;
import org.infinispan.container.InternalEntryFactory;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContextContainer;
import org.infinispan.context.impl.ImmutableContext;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.encoding.DataConversion;
import org.infinispan.eviction.EvictionManager;
import org.infinispan.expiration.ExpirationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.filter.KeyFilter;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.EmptyAsyncInterceptorChain;
import org.infinispan.interceptors.base.CommandInterceptor;
import org.infinispan.jmx.annotations.DataType;
import org.infinispan.jmx.annotations.DisplayType;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.EmbeddedMetadata;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.partitionhandling.AvailabilityMode;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.stats.Stats;
import org.infinispan.stream.impl.local.EntryStreamSupplier;
import org.infinispan.stream.impl.local.KeyStreamSupplier;
import org.infinispan.stream.impl.local.LocalCacheStream;
import org.infinispan.util.DataContainerRemoveIterator;
import org.infinispan.util.TimeService;
import org.infinispan.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Simple local cache without interceptor stack.
* The cache still implements {@link AdvancedCache} since it is too troublesome to omit that.
*
* @author Radim Vansa <[email protected]>
*/
@MBean(objectName = CacheImpl.OBJECT_NAME, description = "Component that represents a simplified cache instance.")
public class SimpleCacheImpl implements AdvancedCache {
private final static Log log = LogFactory.getLog(SimpleCacheImpl.class);
private final static String NULL_KEYS_NOT_SUPPORTED = "Null keys are not supported!";
private final static String NULL_VALUES_NOT_SUPPORTED = "Null values are not supported!";
private final static Class extends Annotation>[] FIRED_EVENTS = new Class[]{
CacheEntryCreated.class, CacheEntryRemoved.class, CacheEntryVisited.class,
CacheEntryModified.class, CacheEntriesEvicted.class, CacheEntryInvalidated.class,
CacheEntryExpired.class};
private final String name;
private DataConversion keyDataConversion;
private DataConversion valueDataConversion;
private ComponentRegistry componentRegistry;
private Configuration configuration;
private EmbeddedCacheManager cacheManager;
private DataContainer dataContainer;
private CacheNotifier cacheNotifier;
private TimeService timeService;
private Metadata defaultMetadata;
private boolean hasListeners = false;
public SimpleCacheImpl(String cacheName) {
this(cacheName, DataConversion.DEFAULT, DataConversion.DEFAULT);
}
public SimpleCacheImpl(String cacheName, DataConversion keyDataConversion, DataConversion valueDataConversion) {
this.name = cacheName;
this.keyDataConversion = keyDataConversion;
this.valueDataConversion = valueDataConversion;
}
@Inject
public void injectDependencies(ComponentRegistry componentRegistry,
Configuration configuration,
EmbeddedCacheManager cacheManager,
DataContainer dataContainer,
CacheNotifier cacheNotifier,
TimeService timeService) {
this.componentRegistry = componentRegistry;
this.configuration = configuration;
this.cacheManager = cacheManager;
this.dataContainer = dataContainer;
this.cacheNotifier = cacheNotifier;
this.timeService = timeService;
componentRegistry.wireDependencies(keyDataConversion);
componentRegistry.wireDependencies(valueDataConversion);
}
@Override
@ManagedOperation(
description = "Starts the cache.",
displayName = "Starts cache."
)
public void start() {
this.defaultMetadata = new EmbeddedMetadata.Builder()
.lifespan(configuration.expiration().lifespan())
.maxIdle(configuration.expiration().maxIdle()).build();
componentRegistry.start();
}
@Override
@ManagedOperation(
description = "Stops the cache.",
displayName = "Stops cache."
)
public void stop() {
if (log.isDebugEnabled())
log.debugf("Stopping cache %s on %s", getName(), getCacheManager().getAddress());
dataContainer = null;
componentRegistry.stop();
}
@Override
public void putForExternalRead(K key, V value) {
ByRef.Boolean isCreatedRef = new ByRef.Boolean(false);
putForExternalReadInternal(key, value, defaultMetadata, isCreatedRef);
}
@Override
public void putForExternalRead(K key, V value, long lifespan, TimeUnit unit) {
Metadata metadata = createMetadata(lifespan, unit);
ByRef.Boolean isCreatedRef = new ByRef.Boolean(false);
putForExternalReadInternal(key, value, metadata, isCreatedRef);
}
@Override
public void putForExternalRead(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
Metadata metadata = createMetadata(lifespan, lifespanUnit, maxIdle, maxIdleUnit);
ByRef.Boolean isCreatedRef = new ByRef.Boolean(false);
putForExternalReadInternal(key, value, metadata, isCreatedRef);
}
@Override
public void putForExternalRead(K key, V value, Metadata metadata) {
ByRef.Boolean isCreatedRef = new ByRef.Boolean(false);
putForExternalReadInternal(key, value, applyDefaultMetadata(metadata), isCreatedRef);
}
protected void putForExternalReadInternal(K key, V value, Metadata metadata, ByRef.Boolean isCreatedRef) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
boolean hasListeners = this.hasListeners;
getDataContainer().compute(key, (k, oldEntry, factory) -> {
// entry cannot be marked for removal in DC but it compute does not deal with expiration
if (isNull(oldEntry)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryCreated(k, value, metadata, true, ImmutableContext.INSTANCE, null);
}
isCreatedRef.set(true);
return factory.create(k, value, metadata);
} else {
return oldEntry;
}
});
if (hasListeners && isCreatedRef.get()) {
cacheNotifier.notifyCacheEntryCreated(key, value, metadata, false, ImmutableContext.INSTANCE, null);
}
}
@Override
public CompletableFuture putAsync(K key, V value, Metadata metadata) {
return CompletableFuture.completedFuture(getAndPutInternal(key, value, applyDefaultMetadata(metadata)));
}
@Override
public Map getAll(Set> keys) {
Map map = CollectionFactory
.makeMap(CollectionFactory.computeCapacity(keys.size()));
for (Object k : keys) {
Objects.requireNonNull(k, NULL_KEYS_NOT_SUPPORTED);
InternalCacheEntry entry = getDataContainer().get(k);
if (entry != null) {
K key = entry.getKey();
V value = entry.getValue();
if (hasListeners) {
cacheNotifier.notifyCacheEntryVisited(key, value, true, ImmutableContext.INSTANCE, null);
cacheNotifier.notifyCacheEntryVisited(key, value, false, ImmutableContext.INSTANCE, null);
}
map.put(key, value);
}
}
return map;
}
@Override
public CacheEntry getCacheEntry(Object k) {
InternalCacheEntry entry = getDataContainer().get(k);
if (entry != null) {
K key = entry.getKey();
V value = entry.getValue();
if (hasListeners) {
cacheNotifier.notifyCacheEntryVisited(key, value, true, ImmutableContext.INSTANCE, null);
cacheNotifier.notifyCacheEntryVisited(key, value, false, ImmutableContext.INSTANCE, null);
}
}
return entry;
}
@Override
public Map> getAllCacheEntries(Set> keys) {
Map> map = CollectionFactory
.makeMap(CollectionFactory.computeCapacity(keys.size()));
for (Object key : keys) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
InternalCacheEntry entry = getDataContainer().get(key);
if (entry != null) {
V value = entry.getValue();
if (hasListeners) {
cacheNotifier.notifyCacheEntryVisited((K) key, value, true, ImmutableContext.INSTANCE, null);
cacheNotifier.notifyCacheEntryVisited((K) key, value, false, ImmutableContext.INSTANCE, null);
}
map.put(entry.getKey(), entry);
}
}
return map;
}
@Override
public Map getGroup(String groupName) {
return Collections.emptyMap();
}
@Override
public void removeGroup(String groupName) {
}
@Override
public AvailabilityMode getAvailability() {
return AvailabilityMode.AVAILABLE;
}
@Override
public void setAvailability(AvailabilityMode availabilityMode) {
throw new UnsupportedOperationException();
}
@Override
public void evict(K key) {
ByRef> oldEntryRef = new ByRef<>(null);
getDataContainer().compute(key, (k, oldEntry, factory) -> {
if (!isNull(oldEntry)) {
oldEntryRef.set(oldEntry);
}
return null;
});
InternalCacheEntry oldEntry = oldEntryRef.get();
if (hasListeners && oldEntry != null) {
cacheNotifier.notifyCacheEntriesEvicted(Collections.singleton(oldEntry), ImmutableContext.INSTANCE, null);
}
}
@Override
public Configuration getCacheConfiguration() {
return configuration;
}
@Override
public EmbeddedCacheManager getCacheManager() {
return cacheManager;
}
@Override
public AdvancedCache getAdvancedCache() {
return this;
}
@Override
public ComponentStatus getStatus() {
return componentRegistry.getStatus();
}
@ManagedAttribute(
description = "Returns the cache status",
displayName = "Cache status",
dataType = DataType.TRAIT,
displayType = DisplayType.SUMMARY
)
public String getCacheStatus() {
return getStatus().toString();
}
protected boolean checkExpiration(InternalCacheEntry entry, long now) {
if (entry.isExpired(now)) {
// we have to check the expiration under lock
return null == dataContainer.compute(entry.getKey(), (key, oldEntry, factory) -> {
if (entry.isExpired(now)) {
cacheNotifier.notifyCacheEntryExpired(key, oldEntry.getValue(), oldEntry.getMetadata(), ImmutableContext.INSTANCE);
return null;
}
return oldEntry;
});
}
return false;
}
@Override
public int size() {
// we have to iterate in order to provide precise result in case of expiration
long now = Long.MIN_VALUE;
int size = 0;
DataContainer dataContainer = getDataContainer();
for (InternalCacheEntry entry : dataContainer) {
if (entry.canExpire()) {
if (now == Long.MIN_VALUE) now = timeService.wallClockTime();
if (!checkExpiration(entry, now)) {
++size;
if (size < 0) {
return Integer.MAX_VALUE;
}
}
} else {
++size;
if (size < 0) {
return Integer.MAX_VALUE;
}
}
}
return size;
}
@Override
public boolean isEmpty() {
long now = Long.MIN_VALUE;
DataContainer dataContainer = getDataContainer();
for (InternalCacheEntry entry : dataContainer) {
if (entry.canExpire()) {
if (now == Long.MIN_VALUE) now = timeService.wallClockTime();
if (!checkExpiration(entry, now)) {
return false;
}
} else {
return false;
}
}
return true;
}
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(Object value) {
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
for (V v : getDataContainer().values()) {
if (Objects.equals(v, value)) return true;
}
return false;
}
@Override
public V get(Object key) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
InternalCacheEntry entry = getDataContainer().get(key);
if (entry == null) {
return null;
} else {
if (hasListeners) {
cacheNotifier.notifyCacheEntryVisited(entry.getKey(), entry.getValue(), true, ImmutableContext.INSTANCE, null);
cacheNotifier.notifyCacheEntryVisited(entry.getKey(), entry.getValue(), false, ImmutableContext.INSTANCE, null);
}
return entry.getValue();
}
}
@Override
public CacheSet keySet() {
return new KeySet();
}
@Override
public CacheCollection values() {
return new Values();
}
@Override
public CacheSet> entrySet() {
return new EntrySet();
}
@Override
public CacheSet> cacheEntrySet() {
return new CacheEntrySet();
}
@Override
public LockedStream lockedStream() {
throw new UnsupportedOperationException("Simple cache doesn't support lock stream!");
}
@Override
public void removeExpired(K key, V value, Long lifespan) {
checkExpiration(getDataContainer().get(key), timeService.wallClockTime());
}
@Override
public AdvancedCache, ?> withEncoding(Class extends Encoder> encoder) {
throw new UnsupportedOperationException();
}
@Override
public AdvancedCache, ?> withEncoding(Class extends Encoder> keyEncoder, Class extends Encoder> valueEncoder) {
throw new UnsupportedOperationException();
}
@Override
public AdvancedCache withWrapping(Class extends Wrapper> wrapper) {
throw new UnsupportedOperationException();
}
@Override
public AdvancedCache withWrapping(Class extends Wrapper> keyWrapper, Class extends Wrapper> valueWrapper) {
throw new UnsupportedOperationException();
}
@Override
public Encoder getKeyEncoder() {
return keyDataConversion.getEncoder();
}
@Override
public Encoder getValueEncoder() {
return valueDataConversion.getEncoder();
}
@Override
public Wrapper getKeyWrapper() {
return keyDataConversion.getWrapper();
}
@Override
public Wrapper getValueWrapper() {
return valueDataConversion.getWrapper();
}
@Override
public DataConversion getKeyDataConversion() {
return keyDataConversion;
}
@Override
public DataConversion getValueDataConversion() {
return valueDataConversion;
}
@Override
@ManagedOperation(
description = "Clears the cache",
displayName = "Clears the cache", name = "clear"
)
public void clear() {
DataContainer dataContainer = getDataContainer();
boolean hasListeners = this.hasListeners;
ArrayList> copyEntries;
if (hasListeners) {
copyEntries = new ArrayList<>(dataContainer.sizeIncludingExpired());
dataContainer.iterator().forEachRemaining(entry -> {
copyEntries.add(entry);
cacheNotifier.notifyCacheEntryRemoved(entry.getKey(), entry.getValue(), entry.getMetadata(), true, ImmutableContext.INSTANCE, null);
});
} else {
copyEntries = null;
}
dataContainer.clear();
if (hasListeners) {
for (InternalCacheEntry entry : copyEntries) {
cacheNotifier.notifyCacheEntryRemoved(entry.getKey(), entry.getValue(), entry.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
}
}
@Override
public String getName() {
return name;
}
@ManagedAttribute(
description = "Returns the cache name",
displayName = "Cache name",
dataType = DataType.TRAIT,
displayType = DisplayType.SUMMARY
)
public String getCacheName() {
String name = getName().equals(BasicCacheContainer.DEFAULT_CACHE_NAME) ? "Default Cache" : getName();
return name + "(" + getCacheConfiguration().clustering().cacheMode().toString().toLowerCase() + ")";
}
@Override
@ManagedAttribute(
description = "Returns the version of Infinispan",
displayName = "Infinispan version",
dataType = DataType.TRAIT,
displayType = DisplayType.SUMMARY
)
public String getVersion() {
return Version.getVersion();
}
@ManagedAttribute(
description = "Returns the cache configuration in form of properties",
displayName = "Cache configuration properties",
dataType = DataType.TRAIT,
displayType = DisplayType.SUMMARY
)
public Properties getConfigurationAsProperties() {
return new PropertyFormatter().format(configuration);
}
@Override
public V put(K key, V value) {
return getAndPutInternal(key, value, defaultMetadata);
}
@Override
public V put(K key, V value, long lifespan, TimeUnit unit) {
Metadata metadata = createMetadata(lifespan, unit);
return getAndPutInternal(key, value, metadata);
}
protected V getAndPutInternal(K key, V value, Metadata metadata) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
ValueAndMetadata oldRef = new ValueAndMetadata<>();
boolean hasListeners = this.hasListeners;
getDataContainer().compute(key, (k, oldEntry, factory) -> {
if (isNull(oldEntry)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryCreated(key, value, metadata, true, ImmutableContext.INSTANCE, null);
}
} else {
oldRef.set(oldEntry.getValue(), oldEntry.getMetadata());
if (hasListeners) {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, oldEntry.getValue(), oldEntry.getMetadata(), true, ImmutableContext.INSTANCE, null);
}
}
if (oldEntry == null) {
return factory.create(k, value, metadata);
} else {
return factory.update(oldEntry, value, metadata);
}
});
V oldValue = oldRef.getValue();
if (hasListeners) {
if (oldValue == null) {
cacheNotifier.notifyCacheEntryCreated(key, value, metadata, false, ImmutableContext.INSTANCE, null);
} else {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, oldValue, oldRef.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
}
return oldValue;
}
@Override
public V putIfAbsent(K key, V value, long lifespan, TimeUnit unit) {
Metadata metadata = createMetadata(lifespan, unit);
return putIfAbsentInternal(key, value, metadata);
}
@Override
public V putIfAbsent(K key, V value, Metadata metadata) {
return putIfAbsentInternal(key, value, applyDefaultMetadata(metadata));
}
protected V putIfAbsentInternal(K key, V value, Metadata metadata) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
ByRef oldValueRef = new ByRef<>(null);
boolean hasListeners = this.hasListeners;
getDataContainer().compute(key, (k, oldEntry, factory) -> {
if (isNull(oldEntry)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryCreated(key, value, metadata, true, ImmutableContext.INSTANCE, null);
}
return factory.create(k, value, metadata);
} else {
oldValueRef.set(oldEntry.getValue());
return oldEntry;
}
});
V oldValue = oldValueRef.get();
if (hasListeners && oldValue == null) {
cacheNotifier.notifyCacheEntryCreated(key, value, metadata, false, ImmutableContext.INSTANCE, null);
}
return oldValue;
}
@Override
public void putAll(Map extends K, ? extends V> map, long lifespan, TimeUnit unit) {
putAllInternal(map, createMetadata(lifespan, unit));
}
@Override
public V replace(K key, V value, long lifespan, TimeUnit unit) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
Metadata metadata = createMetadata(lifespan, unit);
return getAndReplaceInternal(key, value, metadata);
}
@Override
public boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit unit) {
return replaceInternal(key, oldValue, value, createMetadata(lifespan, unit));
}
protected V getAndReplaceInternal(K key, V value, Metadata metadata) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
ValueAndMetadata oldRef = new ValueAndMetadata<>();
boolean hasListeners = this.hasListeners;
getDataContainer().compute(key, (k, oldEntry, factory) -> {
if (!isNull(oldEntry)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, oldEntry.getValue(), oldEntry.getMetadata(), true, ImmutableContext.INSTANCE, null);
}
oldRef.set(oldEntry.getValue(), oldEntry.getMetadata());
return factory.update(oldEntry, value, metadata);
} else {
return oldEntry;
}
});
V oldValue = oldRef.getValue();
if (hasListeners && oldValue != null) {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, oldValue, oldRef.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
return oldValue;
}
@Override
public V put(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
Metadata metadata = createMetadata(lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit);
return getAndPutInternal(key, value, metadata);
}
@Override
public V putIfAbsent(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
Metadata metadata = createMetadata(lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit);
return putIfAbsentInternal(key, value, metadata);
}
@Override
public void putAll(Map extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
putAllInternal(map, createMetadata(lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit));
}
@Override
public V replace(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
Metadata metadata = createMetadata(lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit);
return getAndReplaceInternal(key, value, metadata);
}
@Override
public boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) {
Metadata metadata = createMetadata(lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit);
return replaceInternal(key, oldValue, value, metadata);
}
@Override
public boolean replace(K key, V oldValue, V value, Metadata metadata) {
return replaceInternal(key, oldValue, value, applyDefaultMetadata(metadata));
}
protected boolean replaceInternal(K key, V oldValue, V value, Metadata metadata) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
Objects.requireNonNull(oldValue, NULL_VALUES_NOT_SUPPORTED);
ValueAndMetadata oldRef = new ValueAndMetadata<>();
boolean hasListeners = this.hasListeners;
getDataContainer().compute(key, (k, oldEntry, factory) -> {
V prevValue = getValue(oldEntry);
if (Objects.equals(prevValue, oldValue)) {
oldRef.set(prevValue, oldEntry.getMetadata());
if (hasListeners) {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, prevValue, oldEntry.getMetadata(), true, ImmutableContext.INSTANCE, null);
}
return factory.update(oldEntry, value, metadata);
} else {
return oldEntry;
}
});
if (oldRef.getValue() != null) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryModified(key, value, metadata, oldRef.getValue(), oldRef.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
return true;
} else {
return false;
}
}
@Override
public V remove(Object key) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
ByRef> oldEntryRef = new ByRef<>(null);
boolean hasListeners = this.hasListeners;
getDataContainer().compute((K) key, (k, oldEntry, factory) -> {
if (!isNull(oldEntry)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryRemoved(oldEntry.getKey(), oldEntry.getValue(), oldEntry.getMetadata(), true, ImmutableContext.INSTANCE, null);
}
oldEntryRef.set(oldEntry);
}
return null;
});
InternalCacheEntry oldEntry = oldEntryRef.get();
if (oldEntry != null) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryRemoved(oldEntry.getKey(), oldEntry.getValue(), oldEntry.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
return oldEntry.getValue();
} else {
return null;
}
}
@Override
public void putAll(Map extends K, ? extends V> map) {
putAllInternal(map, defaultMetadata);
}
@Override
public CompletableFuture putAsync(K key, V value) {
return CompletableFuture.completedFuture(put(key, value));
}
@Override
public CompletableFuture putAsync(K key, V value, long lifespan, TimeUnit unit) {
return CompletableFuture.completedFuture(put(key, value, lifespan, unit));
}
@Override
public CompletableFuture putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return CompletableFuture.completedFuture(put(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit));
}
@Override
public CompletableFuture putAllAsync(Map extends K, ? extends V> data) {
putAll(data);
return CompletableFutures.completedNull();
}
@Override
public CompletableFuture putAllAsync(Map extends K, ? extends V> data, long lifespan, TimeUnit unit) {
putAll(data, lifespan, unit);
return CompletableFutures.completedNull();
}
@Override
public CompletableFuture putAllAsync(Map extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
putAll(data, lifespan, lifespanUnit, maxIdle, maxIdleUnit);
return CompletableFutures.completedNull();
}
@Override
public CompletableFuture clearAsync() {
clear();
return CompletableFutures.completedNull();
}
@Override
public CompletableFuture putIfAbsentAsync(K key, V value) {
return CompletableFuture.completedFuture(putIfAbsent(key, value));
}
@Override
public CompletableFuture putIfAbsentAsync(K key, V value, long lifespan, TimeUnit unit) {
return CompletableFuture.completedFuture(putIfAbsent(key, value, lifespan, unit));
}
@Override
public CompletableFuture putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return CompletableFuture.completedFuture(putIfAbsent(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit));
}
@Override
public CompletableFuture removeAsync(Object key) {
return CompletableFuture.completedFuture(remove(key));
}
@Override
public CompletableFuture removeAsync(Object key, Object value) {
return CompletableFuture.completedFuture(remove(key, value));
}
@Override
public CompletableFuture replaceAsync(K key, V value) {
return CompletableFuture.completedFuture(replace(key, value));
}
@Override
public CompletableFuture replaceAsync(K key, V value, long lifespan, TimeUnit unit) {
return CompletableFuture.completedFuture(replace(key, value, lifespan, unit));
}
@Override
public CompletableFuture replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return CompletableFuture.completedFuture(replace(key, value, lifespan, lifespanUnit, maxIdle, maxIdleUnit));
}
@Override
public CompletableFuture replaceAsync(K key, V oldValue, V newValue) {
return CompletableFuture.completedFuture(replace(key, oldValue, newValue));
}
@Override
public CompletableFuture replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit unit) {
return CompletableFuture.completedFuture(replace(key, oldValue, newValue, lifespan, unit));
}
@Override
public CompletableFuture replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit) {
return CompletableFuture.completedFuture(replace(key, oldValue, newValue, lifespan, lifespanUnit, maxIdle, maxIdleUnit));
}
@Override
public CompletableFuture getAsync(K key) {
return CompletableFuture.completedFuture(get(key));
}
@Override
public boolean startBatch() {
// invocation batching implies CacheImpl
throw log.invocationBatchingNotEnabled();
}
@Override
public void endBatch(boolean successful) {
// invocation batching implies CacheImpl
throw log.invocationBatchingNotEnabled();
}
@Override
public V putIfAbsent(K key, V value) {
return putIfAbsentInternal(key, value, defaultMetadata);
}
@Override
public boolean remove(Object key, Object value) {
Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED);
Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED);
ByRef> oldEntryRef = new ByRef<>(null);
boolean hasListeners = this.hasListeners;
getDataContainer().compute((K) key, (k, oldEntry, factory) -> {
V oldValue = getValue(oldEntry);
if (Objects.equals(oldValue, value)) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryRemoved(oldEntry.getKey(), oldValue, oldEntry.getMetadata(), true, ImmutableContext.INSTANCE, null);
}
oldEntryRef.set(oldEntry);
return null;
} else {
return oldEntry;
}
});
InternalCacheEntry oldEntry = oldEntryRef.get();
if (oldEntry != null) {
if (hasListeners) {
cacheNotifier.notifyCacheEntryRemoved(oldEntry.getKey(), oldEntry.getValue(), oldEntry.getMetadata(), false, ImmutableContext.INSTANCE, null);
}
return true;
} else {
return false;
}
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return replaceInternal(key, oldValue, newValue, defaultMetadata);
}
@Override
public V replace(K key, V value) {
return getAndReplaceInternal(key, value, defaultMetadata);
}
@Override
public void addListener(Object listener, KeyFilter super K> filter) {
cacheNotifier.addListener(listener, filter);
if (!hasListeners && canFire(listener)) {
hasListeners = true;
}
}
@Override
public void addListener(Object listener, CacheEventFilter super K, ? super V> filter, CacheEventConverter super K, ? super V, C> converter) {
cacheNotifier.addListener(listener, filter, converter);
if (!hasListeners && canFire(listener)) {
hasListeners = true;
}
}
@Override
public void addListener(Object listener) {
cacheNotifier.addListener(listener);
if (!hasListeners && canFire(listener)) {
hasListeners = true;
}
}
@Override
public void removeListener(Object listener) {
cacheNotifier.removeListener(listener);
}
@Override
public Set
© 2015 - 2025 Weber Informatics LLC | Privacy Policy