88import java .util .Map ;
99import java .util .concurrent .ConcurrentHashMap ;
1010import java .util .logging .Logger ;
11+ import java .util .concurrent .atomic .AtomicBoolean ;
1112
1213/**
1314 * Rate Limiting Filter responsible for limiting the number of requests per client IP.
@@ -29,11 +30,15 @@ public class RateLimitingFilter implements Filter {
2930 private static final long REFILL_TOKENS = 1 ;
3031 private final Duration refillPeriod = Duration .ofSeconds (10 );
3132 private static final int MAX_BUCKETS_THRESHOLD = 1000 ;
33+ private final AtomicBoolean cleanupStarted = new AtomicBoolean (false );
34+ private volatile Thread cleanupThread ;
3235
3336 @ Override
3437 public void init () {
3538 logger .info ("RateLimitingFilter initialized with capacity: " + CAPACITY );
36- startCleanupThread ();
39+ if (cleanupStarted .compareAndSet (false , true )) {
40+ cleanupThread = startCleanupThread ();
41+ }
3742 }
3843
3944 /**
@@ -66,6 +71,12 @@ public void doFilter(HttpRequest request, HttpResponseBuilder response, FilterCh
6671
6772 @ Override
6873 public void destroy () {
74+ Thread t = cleanupThread ;
75+ if (t != null ) {
76+ t .interrupt ();
77+ cleanupThread = null ;
78+ }
79+ cleanupStarted .set (false );
6980 buckets .clear ();
7081 }
7182
@@ -98,8 +109,8 @@ void updateAccess() {
98109 }
99110 }
100111
101- public void startCleanupThread () {
102- Thread .ofVirtual ().start (() -> {
112+ public Thread startCleanupThread () {
113+ return Thread .ofVirtual (). name ( "rate-limit-cleanup" ).start (() -> {
103114 while (!Thread .currentThread ().isInterrupted ()) {
104115 try {
105116 //it checks every 10 minutes
0 commit comments