single thread executor
Ron Pressler
ron.pressler at oracle.com
Fri Sep 4 17:50:18 UTC 2020
Remember, you want multiple virtual threads, but use only on platform
thread to schedule them. So you need to pass the single-thread executor
as the virtual thread scheduler:
ThreadFactory tf = Thread.builder().virtual(Executors.newSingleThreadExecutor()).factory();
And then you can use the thread factory directly to create virtual threads,
or use it like so:
ExecutorService e = Executors.newUnboundedExecutor(tf);
- Ron
On 4 September 2020 at 18:21:45, Miguel Ping (miguel.ping at gmail.com) wrote:
Hi all,
I was experimenting with single thread executor and loom, and I was
expecting that if I have two tasks where the first call goes through
Socket.read, loom would schedule the second one. I'm pretty sure I'm doing
something wrong.
Here's the output I got (I was expecting "Hello world" to appear before
"Connected!"; the program only concludes after I Ctrl+C the netcat process):
$ nc -p 5555 -kl
-- output --
sleeping 1s
Connected!
Hello world
-- java --
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
public class Test {
public static String block() {
// nc -p 5555 -kl
try {
System.out.println("sleeping 1s");
Thread.sleep(1000);
var socket = SocketChannel.open();
socket.connect(new InetSocketAddress("localhost", 5555));
System.out.println("Connected!");
socket.read(ByteBuffer.allocate(10)); // I was hoping this would allow the
other task to be scheduled
return "End";
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
public static String print() {
System.out.println("Hello world");
return "Printed";
}
public static void main(String[] args) throws Throwable {
var e = Executors.newFixedThreadPool(1,
Thread.builder().virtual().factory());
Callable<String> t1 = Test::block;
Callable<String> t2 = Test::print;
var tasks = Arrays.asList(t1, t2);
var fut = e.invokeAll(tasks);
}
}
--
Thanks
More information about the loom-dev
mailing list