Skip to content

Commit

Permalink
Replace guava caches with Caffeine (#2437)
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsDoot authored and Zidane committed Dec 18, 2019
1 parent 06fb67f commit dacb1c5
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@
*/
package org.spongepowered.common.entity.living.human;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.PropertyMap;
Expand Down Expand Up @@ -88,15 +87,11 @@ public class HumanEntity extends CreatureEntity implements TeamMember, IRangedAt

// According to http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape
// you can access this data once per minute, lets cache for 2 minutes
private static final LoadingCache<UUID, PropertyMap> PROPERTIES_CACHE = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MINUTES)
.build(new CacheLoader<UUID, PropertyMap>() {

@Override
public PropertyMap load(final UUID uuid) throws Exception {
return SpongeImpl.getServer().getMinecraftSessionService().fillProfileProperties(new GameProfile(uuid, ""), true)
.getProperties();
}
});
private static final LoadingCache<UUID, PropertyMap> PROPERTIES_CACHE = Caffeine.newBuilder()
.expireAfterWrite(2, TimeUnit.MINUTES)
.build((uuid) -> SpongeImpl.getServer().getMinecraftSessionService()
.fillProfileProperties(new GameProfile(uuid, ""), true)
.getProperties());

// A queue of packets waiting to send to players tracking this human
private final Map<UUID, List<IPacket<?>[]>> playerPacketMap = Maps.newHashMap();
Expand Down Expand Up @@ -330,7 +325,7 @@ private void renameProfile(final String newName) {
}

private boolean updateFakeProfileWithSkin(final UUID skin) {
final PropertyMap properties = PROPERTIES_CACHE.getUnchecked(skin);
final PropertyMap properties = PROPERTIES_CACHE.get(skin);
if (properties.isEmpty()) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V1_6;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
Expand All @@ -69,16 +68,8 @@ public final class ClassEventListenerFactory implements AnnotatedEventListener.F

private final AtomicInteger id = new AtomicInteger();
private final DefineableClassLoader classLoader;
private final LoadingCache<Method, Class<? extends AnnotatedEventListener>> cache = CacheBuilder.newBuilder()
.concurrencyLevel(1)
.weakValues()
.build(new CacheLoader<Method, Class<? extends AnnotatedEventListener>>() {

@Override
public Class<? extends AnnotatedEventListener> load(Method method) throws Exception {
return ClassEventListenerFactory.this.createClass(method);
}
});
private final LoadingCache<Method, Class<? extends AnnotatedEventListener>> cache = Caffeine.newBuilder()
.weakValues().build(this::createClass);
private FilterFactory filterFactory;

private final String targetPackage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@
package org.spongepowered.common.event;

import com.google.common.base.CaseFormat;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.reflect.TypeToken;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.SpongeEventFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,22 @@
*/
package org.spongepowered.common.event.filter;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.spongepowered.common.event.gen.DefineableClassLoader;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public class FilterFactory {

private final AtomicInteger id = new AtomicInteger();
private final DefineableClassLoader classLoader;
private final LoadingCache<Method, Class<? extends EventFilter>> cache = CacheBuilder.newBuilder()
.concurrencyLevel(1).weakValues().build(new CacheLoader<Method, Class<? extends EventFilter>>() {

@Override
public Class<? extends EventFilter> load(Method method) throws Exception {
return FilterFactory.this.createClass(method);
}
});
private final LoadingCache<Method, Class<? extends EventFilter>> cache = Caffeine.newBuilder()
.weakValues().build(this::createClass);
private final String targetPackage;

public FilterFactory(String targetPackage, DefineableClassLoader classLoader) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@
*/
package org.spongepowered.common.service.permission;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import org.spongepowered.api.command.CommandSource;
Expand Down Expand Up @@ -72,22 +71,19 @@ private static InetAddress getAddress(RemoteSource input, Function<RemoteConnect
}

private LoadingCache<RemoteSource, Set<Context>> buildAddressCache(final String contextKey, final Function<RemoteSource, InetAddress> function) {
return CacheBuilder.newBuilder()
return Caffeine.newBuilder()
.weakKeys()
.build(new CacheLoader<RemoteSource, Set<Context>>() {
@Override
public Set<Context> load(RemoteSource key) {
ImmutableSet.Builder<Context> builder = ImmutableSet.builder();
final InetAddress addr = function.apply(key);
if (addr == null) {
return builder.build();
}
builder.add(new Context(contextKey, addr.getHostAddress()));
for (String set : Maps.filterValues(SpongeImpl.getGlobalConfigAdapter().getConfig().getIpSets(), input -> input.apply(addr)).keySet()) {
builder.add(new Context(contextKey, set));
}
.<RemoteSource, Set<Context>>build((key) -> {
ImmutableSet.Builder<Context> builder = ImmutableSet.builder();
final InetAddress addr = function.apply(key);
if (addr == null) {
return builder.build();
}
builder.add(new Context(contextKey, addr.getHostAddress()));
for (String set : Maps.filterValues(SpongeImpl.getGlobalConfigAdapter().getConfig().getIpSets(), input -> input.apply(addr)).keySet()) {
builder.add(new Context(contextKey, set));
}
return builder.build();
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@

import static com.google.common.base.Preconditions.checkNotNull;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalListener;
import com.google.common.base.Objects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.collect.ImmutableMap;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
Expand Down Expand Up @@ -117,28 +117,26 @@ public SqlServiceImpl() {
public void buildConnectionCache() {
this.connectionCache = null;
this.connectionCache =
CacheBuilder.newBuilder().removalListener((RemovalListener<ConnectionInfo, HikariDataSource>) notification -> {
HikariDataSource source = notification.getValue();
if (source != null) {
source.close();
}
}).build(new CacheLoader<ConnectionInfo, HikariDataSource>() {
@Override
public HikariDataSource load(@Nonnull ConnectionInfo key) throws Exception {
HikariConfig config = new HikariConfig();
config.setUsername(key.getUser());
config.setPassword(key.getPassword());
config.setDriverClassName(key.getDriverClassName());
// https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing for info on pool sizing
config.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1);
config.setLeakDetectionThreshold(60 * 1000);
Properties driverSpecificProperties = PROTOCOL_SPECIFIC_PROPS.get(key.getDriverClassName());
if (driverSpecificProperties != null) {
config.setDataSourceProperties(driverSpecificProperties);
}
config.setJdbcUrl(key.getAuthlessUrl());
return new HikariDataSource(config);
Caffeine.newBuilder()
.removalListener(((key, value, cause) -> {
HikariDataSource source = value;
if (source != null) {
source.close();
}
})).build((key) -> {
HikariConfig config = new HikariConfig();
config.setUsername(key.getUser());
config.setPassword(key.getPassword());
config.setDriverClassName(key.getDriverClassName());
// https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing for info on pool sizing
config.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1);
config.setLeakDetectionThreshold(60 * 1000);
Properties driverSpecificProperties = PROTOCOL_SPECIFIC_PROPS.get(key.getDriverClassName());
if (driverSpecificProperties != null) {
config.setDataSourceProperties(driverSpecificProperties);
}
config.setJdbcUrl(key.getAuthlessUrl());
return new HikariDataSource(config);
});
}
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,10 @@
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spongepowered.common.util.SpongeCommonTranslationHelper.t;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
Expand All @@ -50,6 +49,7 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class SpongeCallbackHolder {
Expand All @@ -58,20 +58,17 @@ public class SpongeCallbackHolder {
private static final SpongeCallbackHolder INSTANCE = new SpongeCallbackHolder();

static final ConcurrentMap<UUID, Consumer<CommandSource>> reverseMap = new ConcurrentHashMap<>();
private static final LoadingCache<Consumer<CommandSource>, UUID> callbackCache = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES)
.removalListener(new RemovalListener<Consumer<CommandSource>, UUID>() {
@Override
public void onRemoval(RemovalNotification<Consumer<CommandSource>, UUID> notification) {
reverseMap.remove(notification.getValue(), notification.getKey());
}
})
.build(new CacheLoader<Consumer<CommandSource>, UUID>() {
@Override
public UUID load(Consumer<CommandSource> key) throws Exception {
UUID ret = UUID.randomUUID();
reverseMap.putIfAbsent(ret, key);
return ret;
private static final LoadingCache<Consumer<CommandSource>, UUID> callbackCache = Caffeine.newBuilder()
.expireAfterAccess(10, TimeUnit.MINUTES)
.removalListener(((key, value, cause) -> {
if (value != null) {
reverseMap.remove(value);
}
}))
.build((key) -> {
UUID ret = UUID.randomUUID();
reverseMap.putIfAbsent(ret, key);
return ret;
});


Expand All @@ -81,7 +78,7 @@ public static SpongeCallbackHolder getInstance() {


public UUID getOrCreateIdForCallback(Consumer<CommandSource> callback) {
return callbackCache.getUnchecked(checkNotNull(callback, "callback"));
return callbackCache.get(checkNotNull(callback, "callback"));
}

public Optional<Consumer<CommandSource>> getCallbackForUUID(UUID id) {
Expand Down

0 comments on commit dacb1c5

Please sign in to comment.