0

Here inside the for loop I'm trying to get the value from stringCompletableFutureEntry which throws the InterruptedException and with sonar enabled on this, I am supposed to interrupt the thread when an exception occurs but according to my expectation I should get data for all futures if it's not there than I can use Optional.empty() or skip this iteration and move further. How should I get rid of this sonar issue?

private void mapFutures(
      Map<Obj1, CompletableFuture<DummyContainer>> futures, List<DummyStatus> dummyStatusList) {
    for (Map.Entry<Obj1, CompletableFuture<DummyContainer>> stringCompletableFutureEntry :
        futures.entrySet()) {
      try {
        Optional<DummyContainer> dummyContainer =
            Optional.ofNullable(**stringCompletableFutureEntry.getValue().get()**);
        List<Dummy> dummy = null;
        dummy = dummyContainer.map(DummyContainer::getDummyData).orElseGet(() -> null);
        
        if (!CollectionUtils.isEmpty(dummy)) {
          dummyStatusList.add(new DummyStatus(stringCompletableFutureEntry.getKey(), dummy.get(0)));
        } else {
          dummyStatusList.add(new DummyStatus(stringCompletableFutureEntry.getKey()));
        }
      } catch (InterruptedException | ExecutionException e) {
        Thread.currentThread().interrupt(); // sonar expectation
      }
    }
  }

I tried using timeout while getting data e.g.

stringCompletableFutureEntry.getValue().get(Long.parseLong("3000"), TimeUnit.MILLISECONDS))

It'll throw a TimeoutException once the time threshold is reached.

I'm looking for other Solutions to get rid of InterruptedException inside the loop.

Ryednap
  • 324
  • 1
  • 9
Shailja
  • 1
  • 1
  • Does this answer your question? [Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?](https://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-in-a-catch-interruptexception-block) – Didier L Jan 03 '23 at 09:16
  • @DidierL Since I need to interrupt the thread here, do we have any other approach with which I can avoid getting InterruptedException? I'm using Executor Service and I don't want the output to get effected due to one iteration failure. Please suggest me the best way to handle it. – Shailja Jan 04 '23 at 00:21
  • @DidierL I've also tried checking the interrupted flag - if its true used Optional.empty() but with this I stucked to this Exception - Interrupted acquiring a permit to retrieve an item from the pool ; nested exception is com.mongodb.MongoInterruptedException: Interrupted acquiring a permit to retrieve an item from the pool – Shailja Jan 04 '23 at 00:23

0 Answers0