0

Please tell me how I can solve such thing? While I am trying to interrupt getting image from url through Spring WebFlux webClient - it does not stop.

I have next code

method1(){
...
ExecutorService executor = Executors.newFixedThreadPool(3);

for (String url: urlList){
  executor.submit(
    () -> {

      //byte[] byteImage = getImage(url)

      //save in file system (byteImage)

      //save in DB (byteImage)

      //save in redis (byteImage)
    }
)}
...
}

  public byte[] getImage(String url) {


    byte[] result = null;

    try {
      webClient
          .get()
          .uri(url)
          .header("X-Requested-With", "XMLHttpRequest")
          .exchange()
          .flatMap(response -> {
            if (!response.statusCode().is2xxSuccessful()) {
              return Mono.error(new RuntimeException("Internal server error"));
            } else {
              return response.bodyToMono(ByteArrayResource.class);
            }
          }).map(ByteArrayResource::getByteArray)
          .block();
    } catch (Exception e) {
        log.warn("can't take screenshot {}", url);
    }

    return result;
  }

in another thread I try to interrupt all executor threads by executor.shutdownNow()

If I remove webClient #block() - everything ok. All threads successfully interrupted and the process stops.

But if the webClient has block() method the executor can't stop execution.

Help please, how can I solve this issue?

r.gomboev
  • 73
  • 5

1 Answers1

0

I found the solution. The problem was that when I catch InterruptedException the flag "interrupted" resets. Another problem was when block throw an Exception it's throws wrapped InterruptedException

and if I try to catch and again set flag InterruptedException it was not go inside the condition, like

if (e instanceof InterruptedException){
  Thread.currentThread().interrupt(); << this is never called
}

and the solution was:

if (Exceptions.unwrap(e) instanceof InterruptedException){
  Thread.currentThread().interrupt(); << this is never called
}
r.gomboev
  • 73
  • 5