My requirement is to poll MongoDB every 30s for any data change in a collection. I have used Java CompletableFuture.runAsync to implement this feature as code captured below. I have test run the program for a day and it seems working fine.
My questions are:
My threadpool size is 3, from the log file I found that the first few 2 runs are using pool-1-thread-1 and pool-1-thread-2, from the third run and so on it keeps reusing pool-1-thread-3 for some time, then reuse pool-1-thread-1/pool-1-thread-2 for certain period of time... would there be any potential issue or is it normal?
private static ExecutorService executor = Executors.newFixedThreadPool(3); private void watch(){ CompletableFuture<Void> watchForLeadershipChange = CompletableFuture.runAsync(() -> pollForChanges(), executor); } private void pollForChanges() { //Query MongoDB collection and do some logic TimeUnit.SECONDS.sleep(30); watch(); }
pollForChanges()
calls watch()
, the subsequent invocations of pollForChanges()
are happening asynchronously in (probably) another thread. In either case it will always have a fresh stack pointer. ExecutorService
chooses is an implementation detail of that ExecutorService
. There is nothing odd or unexpected about the behavior you are observing. All of that being said - this is a very roundabout way of doing something very trivial with a ScheduledExecutorService
as was pointed out in comments:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay(
() -> queryMongoAndDoSomeLogic(),
0,
30,
TimeUnit.SECONDS);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.