6 Nisan 2023 Perşembe

Executors.newVirtualThreadPerTaskExecutor metodu

Giriş
Virtual Threads aslında ForkJoinPool üzerinde çalışır. Project Loom ile geliyor

Örnek
Şöyle yaparız
private static void virtualThreadsDemo(int numberOfThreads) {
  try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, numberOfThreads).forEach(i -> {
      executor.submit(() -> {
        Thread.sleep(Duration.ofMillis(1));
        return i;
      });
    });
  }
}
Örnek
Şöyle yaparız
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
  for (int i = 1; i <= 10; i++) {
    String taskName = "Task" + i;
    executor.execute(() -> someWork(taskName));
  }
}
Çıktı şöyle
VirtualThread[#25]/runnable@ForkJoinPool-1-worker-4 executing Task4
VirtualThread[#26]/runnable@ForkJoinPool-1-worker-5 executing Task5
VirtualThread[#28]/runnable@ForkJoinPool-1-worker-7 executing Task7
VirtualThread[#23]/runnable@ForkJoinPool-1-worker-2 executing Task2
VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 executing Task1
VirtualThread[#24]/runnable@ForkJoinPool-1-worker-3 executing Task3
VirtualThread[#27]/runnable@ForkJoinPool-1-worker-6 executing Task6
VirtualThread[#29]/runnable@ForkJoinPool-1-worker-8 executing Task8
VirtualThread[#32]/runnable@ForkJoinPool-1-worker-3 executing Task10
VirtualThread[#31]/runnable@ForkJoinPool-1-worker-8 executing Task9
VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1 completed Task5
VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 completed Task1
VirtualThread[#25]/runnable@ForkJoinPool-1-worker-9 completed Task4
VirtualThread[#24]/runnable@ForkJoinPool-1-worker-2 completed Task3
VirtualThread[#27]/runnable@ForkJoinPool-1-worker-2 completed Task6
VirtualThread[#32]/runnable@ForkJoinPool-1-worker-9 completed Task10
VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1 completed Task7
VirtualThread[#23]/runnable@ForkJoinPool-1-worker-7 completed Task2
VirtualThread[#31]/runnable@ForkJoinPool-1-worker-6 completed Task9
VirtualThread[#29]/runnable@ForkJoinPool-1-worker-1 completed Task8

Hiç yorum yok:

Yorum Gönder