-
Notifications
You must be signed in to change notification settings - Fork 2
Time based Counting
Sometimes it is needed to count how many times did something happen in a certain period of time, for example, how many people have logged in within the last 12 hours, or something like that. kantanj provides a simple to use ExpiringList
object for this purpose. You can find it in package me.darksidecode.kantanj.time
.
Let's take kantanj's IP/geolocations API's utility class as an example. It uses ExpiringList
(by the way, the object was called that way because it's basically a list of Long
s) to count the number of requests to the online service it is based on within the last minute.
1. Create an ExpiringList
. You should do this somewhere when you initialize your counter. Then you will use this object every time you want to count an event.
private static final ExpiringList requestCounter = new ExpiringList(1, TimeUnit.MINUTES);
The constructor takes two parameters, which both relate to the period of entry deletion (or, in other words, single entry/event lifespan). In the above example, events will be "forgotten" in one minute after insertion.
2. Update and count. Use method updateAndCount()
to update the counter: add one entry (current time millis) to the list, and remove all entries that are "outdated" (which have been inserted over lifespan
(constructor parameters) time ago). The method will return the current number of "fresh" entries, including the just inserted one. This means that the least value the method may ever return is always one (1
).
int requestsLastMin = requestCounter.updateAndCount();
if ((requestsLastMin > MAX_REQUESTS_PER_MIN) && (blockOnLimitExcess))
// Block to avoid getting our IP banned.
Threads.sleepQuietly(threadBlockMillis);
In the above example, we count one more request and remove all other counted requests that were made more than a minute ago. The new number of requests (the current number of requests in the last minute) is then stored in variable requestsLastMin
.