#How to avoid editing data in a cache when using LoadingCache?

1 messages · Page 1 of 1 (latest)

hazy crow
#

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

vale cloakBOT
#

<@&987246652869971988> please have a look, thanks.

vale cloakBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.