Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a Guava Cache with the value as number of hits?

Tags:

java

guava

I'm trying to implement a cache which will count the number of login attempts in the last 5 minutes, in my code i want to check if the user has attempted more than MAX_ATTEMPTS.

In all the code examples i found online for "Guava Cache" use the load method to fetch the value from some other source or calculate it using some method, how can i increment it every time there is a cache hit ?

static LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
    .maximumSize(100000)
    .expireAfterAccess(5, TimeUnit.MINUTES)
    .build(
            new CacheLoader<String, Integer>() {
                public Integerload(String user) {
                       return ????;
                }
            }
    );

later at runtime i would like to check:

if(cache.getIfPresent(user) != null && cache.get(user) > MAX_ATTEMPTS)

and also increment it if:

if(cache.getIfPresent(user) != null && cache.get(user) <= MAX_ATTEMPTS)
like image 776
Oren Avatar asked Sep 15 '25 04:09

Oren


1 Answers

@Oren Your solution isn't thread-safe, since you're operating on a value outside Cache. You'd better use Cache#asMap() view and change value inside ConcurrentMap#compute(K, BiFunction<K, V, V>) method:

forgetPasswordCache.asMap().compute(email, (cachedEmail, currentCount) -> {
  if (currentCount != null && currentCount >= RESET_PASSWORD_MAX_ATTEMPTS) {
    logger.error("User with id: " + user.getId() + " and email: " + email +
         " has reached the maximum number of reset password attempts, the mail will not be sent");
    return null;
  }

  if (currentCount == null) {
    return 1;
  } else {
    return currentCount + 1;
  }
});
like image 187
Xaerxess Avatar answered Sep 16 '25 18:09

Xaerxess