... continued
Explore how to implement a token bucket filter using Java multithreading. This lesson guides you through managing tokens with synchronized methods, using a background daemon thread for token addition, and applying the factory design pattern to ensure proper thread management. Understand techniques for safe concurrency and how to coordinate threads to grant tokens at regular intervals.
We'll cover the following...
Solution using a background thread
The previous solution consisted of manipulating pointers in time, thus avoiding threads altogether. Another solution is to use threads to solve the token bucket filter problem. We instantiate one thread to add a token to the bucket after every one second. The user thread invokes the getToken() method and is granted one if available.
One simplification as a result of using threads is we now only need to remember the current number of tokens held by the token bucket filter object. We'll add an additional method daemonThread() that will be executed by the thread that adds a token every second to the bucket. The skeleton of our class looks as follows:
public class MultithreadedTokenBucketFilter {
private long possibleTokens = 0;
private final int MAX_TOKENS;
private final int ONE_SECOND = 1000;
public MultithreadedTokenBucketFilter(int maxTokens) {
MAX_TOKENS = maxTokens;
}
private void daemonThread() {
}
void getToken() throws InterruptedException
{
}
}
The ...