Guava is very useful.
Now, I want to implement a limit for access counter in a period.(e.g. max 3 times in one hours people can do it)
Use Guava’s mapMarker or cache is very easy….(like using memcached), but I meet some concurrent problem when increase counter in map.
Could Guava support the incr operation like in memcache? when map’s value is integer? or make a new util class for that…
You could store a
Semaphore(link) instead of a normal integer. Look at methodtryAcquire(). For periodically resetting the number of permits, you can use a combination ofdrain()andrelease(). If draining the permit for a brief period is problematic, you could also useAtomicIntegerand do something like this:1) Peek the current value with
get()2) If there is still quota available, attempt to acquire one quota by performing
compareAndSet(oldValue, oldValue + 1).3) If the value is successfully updated (i.e. true is returned), the thread is allowed to proceed. If not, the thread must retry from (1).
4) To reset the number of permits, use
set()