To replace the Cache2k usage with a LoadingCache from Guava or Caffeine, you need to set up a cache loader since LoadingCache provides automatic loading and doesn't require explicit put operations. Here's how you can modify the code to use a LoadingCache:
Using Guava's LoadingCache:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import java.util.concurrent.ExecutionException;
private static final String CACHE_NAME = "labeledDtoCache"; // This won't be used directly as in Cache2k
private static final LoadingCache<Enum<?>, LabeledEnumDto> cache = CacheBuilder.newBuilder()
.maximumSize(250)
.build(new CacheLoader<Enum<?>, LabeledEnumDto>() {
@Override
public LabeledEnumDto load(Enum<?> e) throws Exception {
if (e == null) {
return null;
}
String name = (String) FieldUtils.readDeclaredField(e, "name", true);
return new LabeledEnumDto(e.name(), name);
}
});
@Override
public LabeledEnumDto dto(Enum<?> e) {
if (e == null) {
return null;
}
try {
// Guava returns null if a null value is mapped, which is not very common.
return cache.get(e);
} catch (ExecutionException ex) {
throw new RuntimeException("LabeledEnumDto mapping failed", ex);
}
}
Using Caffeine's LoadingCache:
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
private static final String CACHE_NAME = "labeledDtoCache"; // This isn't used directly in Caffeine either
private static final LoadingCache<Enum<?>, LabeledEnumDto> cache = Caffeine.newBuilder()
.maximumSize(250)
.build(e -> {
if (e == null) {
return null;
}
try {
String name = (String) FieldUtils.readDeclaredField(e, "name", true);
return new LabeledEnumDto(e.name(), name);
} catch (IllegalAccessException ex) {
throw new RuntimeException("LabeledEnumDto mapping failed", ex);
}
});
@Override
public LabeledEnumDto dto(Enum<?> e) {
if (e == null) {
return null;
}
// Caffeine handles null value mapping by simply returning null.
return cache.get(e);
}
Key Points:
- Automatic Loading: Both Guava and Caffeine
LoadingCache automatically load the value when it's not present, reducing the need for explicit cache put operations.
- Error Handling: Ensure you handle exceptions during cache loading appropriately. The
CacheLoader used in Guava can throw exceptions which need to be caught, while Caffeine offers a more streamlined lambda-based approach.
- Size Limitation: Both implementations set a maximum number of entries (
maximumSize(250)), similar to the entryCapacity in Cache2k.