Skip to content

Commit

Permalink
Make threads deamon and lower max backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
Edwin-192 committed Jan 3, 2024
1 parent 6d313c0 commit dc4c4d9
Showing 1 changed file with 11 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheUpdateEvent;

import io.micrometer.core.instrument.util.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -50,9 +52,10 @@ public JedisCacheListener(JedisPool jedisPool, String cacheName, Class<K> keyTyp
}

public void subscribe() {
new Thread(() -> {
Thread thread = new Thread(() -> {
AtomicInteger reconnectBackoffTimeMillis = new AtomicInteger(1000);
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
// Using a NamedThreadFactory for creating a Daemon thread, so it will never block the jvm from closing.
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("reset-reconnect-backoff-thread"));
ScheduledFuture<?> resetTask = null;

while(!Thread.currentThread().isInterrupted() && !this.jedisPool.isClosed()){
Expand All @@ -75,14 +78,16 @@ public void subscribe() {
// Wait before trying to reconnect and increase the backoff duration
try {
Thread.sleep(reconnectBackoffTimeMillis.get());
//exponential increase backoff with a max of 1 minute
reconnectBackoffTimeMillis.set(Math.min((reconnectBackoffTimeMillis.get() * 2), 60000));
// exponentially increase the backoff with a max of 30 seconds
reconnectBackoffTimeMillis.set(Math.min((reconnectBackoffTimeMillis.get() * 2), 30000));
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
// ignored, already interrupted so the while loop will stop
}
}
}
}, "JedisSubscriberThread").start();
}, "JedisSubscriberThread");
thread.setDaemon(true);
thread.start();
}

@Override
Expand Down

0 comments on commit dc4c4d9

Please sign in to comment.