Created
March 24, 2024 23:02
-
-
Save dhinojosa/f831e102de1c7c3733919baf8e5fcd03 to your computer and use it in GitHub Desktop.
The following hangs when using ExecutorService in TWR block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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