Future.getはforkjoinpool / workstealingpoolでスレッドをブロックすることはできません

ゼロ :

future.get()はスレッドをブロックしていないようだ1として、私はworkstealingpoolのサイズを設定します。

@Test
public void runAsyncThenApplyExample() {
    ExecutorService executor = Executors.newWorkStealingPool(1);
    CompletableFuture cf = CompletableFuture.supplyAsync(
            () -> {
                //assertTrue(Thread.currentThread().isDaemon());
                System.out.println("func: " + threadName());
                Callable<Long> callable = () ->stub();
                Future<Long> future = executor.submit(callable);
                try {
                    future.get();  <<<<< **I think this should block the thread**
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                return 1;
            }, executor).thenAccept(s -> {
        System.out.println("accept: " + threadName());
    });
    //assertFalse(cf.isDone());
    System.out.println("main: " + threadName());
    sleep(10);
    assertTrue(cf.isDone());
}

private Long stub() {
    System.out.println("stub: " + threadName());
    return 1L;
}
private String threadName() {
    return Thread.currentThread().getName();
}

出力:

FUNC:ForkJoinPool-1-労働者-3
メイン:メイン
スタブ:ForkJoinPool-1-労働者-3
受け入れる:ForkJoinPool-1-労働者-3

Future.get()とスタブが同じthreeadを使用しているようです。 ここでは、画像の説明を入力します。

ここでは、画像の説明を入力します。

オレグ:

Executors.newWorkStealingPool(1);用途ForkJoinPool補償スレッドと呼ばれる文書化されていない機能があります。

http://www.coopsoft.com/ar/CalamityArticle.html(強調鉱山):

JDK1.8で導入CompletableFutureクラスです。Javadocを引用すると:

“A Future that may be explicitly completed (setting its value and status), and may include dependent functions and actions that trigger upon its completion.”

Not mentioned in the JavaDoc is that when using a large number of dependent functions with a get() method, the framework creates “compensation threads” to continue fetching application tasks from the deques and submission queue.

So when you do future.get(); it blocks but another thread is created in which the task is executed.

When running your code the output I'm getting is:

func: ForkJoinPool-1-worker-1
main: main
stub: ForkJoinPool-1-worker-0
accept: ForkJoinPool-1-worker-1

あなたは、あなたを示していないthreadName()方法を多分あり、その中に及びので、あなたが同じスレッド名を見ていること(あるいはあなたがそのような場合には同じ名前を使用して別のJVMを使用して、スレッドIDを確認してください)の間違い?ない場合は、同じスレッドとしてFUNCとスタブを出力し、完全なコードを提供してください。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=214685&siteId=1