Skip to main content

Jackson

added in: Xanthic v0.5.0

requires: Jackson v2.16+

Description

Jackson relies upon caching during serialization, deserialization, and type resolution.

By default, Jackson relies upon LRUMap, which utilizes a modified ConcurrentLinkedHashMap (CLHM) implementation. CLHM has not been updated in nearly a decade, and its author suggests alternatives such as Caffeine.

This module allows you to easily delegate Jackson's caching to your preferred Xanthic cache implementation.

Installation

build.gradle
dependencies {
implementation 'io.github.xanthic.cache:cache-jackson'
}

Usage

When building a Jackson Mapper, simply specify cacheProvider with an instance of XanthicJacksonCacheProvider.

In addition, you must have a backing cache implementation on your classpath for Xanthic to utilize.

Defaults

XanthicJacksonCacheProvider's default instance uses the recommended maximum cache sizes defined by Jackson developers:

ObjectMapper mapper = JsonMapper.builder()
.cacheProvider(XanthicJacksonCacheProvider.defaultInstance())
.build();

Here, Xanthic will use the default cache provider stored within CacheApiSettings.

Custom

Alternatively, you can customize the cache specifications used for the deserializer cache, serializer cache, and type factory.

In the simplest case, this customization can take the form of different maximum cache sizes:

long deserCapacity = 2048;
long serCapacity = 4096;
long typesCapacity = 256;

ObjectMapper mapper = JsonMapper.builder()
.cacheProvider(new XanthicJacksonCacheProvider(deserCapacity, serCapacity, typesCapacity))
.build();

 

Alternatively, your customization can involve more complex adjustments like entry expiry and removal listeners. Theoretically, you could even mix-and-match different backing implementations via spec.provider.

CacheProvider provider = new XanthicJacksonCacheProvider(
// for deserialization
spec -> spec.maxSize(2048L)
.expiryType(ExpiryType.POST_ACCESS)
.expiryTime(Duration.ofMinutes(4)),
// for serialization
spec -> spec.maxSize(4096L)
.expiryType(ExpiryType.POST_WRITE)
.expiryTime(Duration.ofMinutes(5)),
// for type factory
spec -> spec.maxSize(256L)
.removalListener((key, value, cause) -> {})
);

ObjectMapper mapper = JsonMapper.builder()
.cacheProvider(provider)
.build();