Skip to content

Instantly share code, notes, and snippets.

@dhinojosa
Created March 24, 2024 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhinojosa/f831e102de1c7c3733919baf8e5fcd03 to your computer and use it in GitHub Desktop.
Save dhinojosa/f831e102de1c7c3733919baf8e5fcd03 to your computer and use it in GitHub Desktop.
The following hangs when using ExecutorService in TWR block
package com.evolutionnext.demo.virtualthreads;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.*;
public class VirtualThreadsTryWithResources {
public static void main(String[] args) {
try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Long> submit = executorService.submit(() -> {
try (InputStream inputStream = new URI("https://openjdk.org/").toURL().openStream();
InputStreamReader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in)) {
return reader.lines()
.flatMap(line -> Arrays.stream(line.split("\\W+")))
.filter(word -> word.equalsIgnoreCase("java"))
.count();
}
});
System.out.println("Submitted");
//The timeout is not respected here
System.out.println(submit.get(1, TimeUnit.SECONDS));
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment