Junior — Middle
What is the most common solution for storing temporary data in memory in Java?
sobes.tech AI
Answer from AI
The most common solution for storing temporary data in memory in Java is using caching with libraries such as:
- Ehcache — a popular cache supporting various data storage and lifetime management strategies.
- Caffeine — a modern, high-performance cache with support for automatic removal of stale entries.
- Guava Cache — a cache from the Google Guava library, easy to use.
Example of using Caffeine:
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(10, java.util.concurrent.TimeUnit.MINUTES)
.maximumSize(1000)
.build();
cache.put("key", "value");
String value = cache.getIfPresent("key");
For distributed caching, Redis is often used, but it is an external storage, not purely in-memory in JVM.