I'm currently developing a plugin for profiles. I added caching via LoadingCache, but when I get a profile from the cache, it returns a reference, so if I edit something in the received profile, it will be edited in the cache. How to avoid it? Create a copy constructor or something similar?
private final LoadingCache<String, Optional<Profile>> cache = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build(CacheLoader.from(this::getProfileFromDatabase));
public Profile findByPlayerName(String playerName) {
try {
return cache.get(playerName.toLowerCase())
.orElse(null);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
// tests
Profile profile = profileManager.findByPlayerName("omashune"); // age = 18
profile.setAge(19); // age = 19
profileManager.findByPlayerName("omashune"); // age = 19