简体   繁体   中英

Java CompletableFuture.runAsync recurrsion … any potential risk?

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:

  1. Would there be any potential risk of OOM "stack overflow" exception if I keep running for long time?
  2. 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(); } 
  1. Would there be any potential risk of OOM "stack overflow" exception if I keep running for long time? No. While 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.
  2. My threadpool size is 3, from the log file I found that the first few 2 runs… Which thread the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM