English 中文(简体)
Java 21 结构化
原标题:Java 21 Structured Concurrency ShutdownOnSuccess and ShutdownOnFailure understanding
  • 时间:2024-02-22 14:46:40
  •  标签:
  • java
  • java-21

我正试图理解目前瓦 Java21中正在审查的有条理的一致意见(JEP 453 )。

我有这个例子:使用<代码>的Im。 ShutdownOn Success and ShutdownOnFailure

如java docs所述,

  • ShutdownOn Success抓住了第一个结果,关闭了工作范围,以打断未完工的路面,并提醒所有人。 这一类别针对的是任何子公司(“任何”)的结果以及不需要等待其他未完成任务结果的情况。 它界定了取得第一种结果的方法,或者如果所有的子公司都失败,就放弃一种例外。

  • ShutdownOnFailure抓住了第一个例外,并缩小了任务范围。 这一类别针对的是需要所有子公司(“所有”)结果的情况;如果任何子公司未能做到这一点,则不再需要其他未完成子公司的结果。 如果亚特克人中任何一个都失败,如果界定了放弃例外的方法。

what I understand is in ShutdownOnSuccess case if one task get completed rest will be interrupted and in ShutdownOnFailure all task needs to be completed , then shutdown call is made.

因此,完成交给成功的任务的时间将减少失败。 这种理解是否正确?

如果是,那么完成时间 成功比每次处决失败大,原因何在?

这里是样本代码。

package com.example.threadex;

import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;

public class StructuredTaskScopeExample {
    public static void main(String[] args) {
        Instant start = Instant.now();
        try(var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()){
            Subtask<String> task1 = scope.fork(Weather::getTempFromA);
            Subtask<String> task2 = scope.fork(Weather::getTempFromB);
            Subtask<String> task3 = scope.fork(Weather::getTempFromC);
            scope.join();
            System.out.println(STR."""
                    task1: {task1.state()}: result : {task1.state() == Subtask.State.SUCCESS ? task1.get() : "Not Available"}
                    task2: {task2.state()}: result : {task2.state() == Subtask.State.SUCCESS ? task2.get() : "Not Available"}
                    task3: {task3.state()}: result : {task3.state() == Subtask.State.SUCCESS ? task3.get() : "Not Available"}
                    """);

        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        System.out.println(STR."AnySuccess : {Duration.between(start, Instant.now()).toMillis()}ms");
        System.out.println("==================");
        Instant start1 = Instant.now();
        try(var scope1 = new StructuredTaskScope.ShutdownOnFailure()){
            Subtask<String> task1 = scope1.fork(Weather::getTempFromA);
            Subtask<String> task2 = scope1.fork(Weather::getTempFromB);
            Subtask<String> task3 = scope1.fork(Weather::getTempFromC);
            scope1.join();
            scope1.throwIfFailed(RuntimeException::new);
            System.out.println(STR."""
                    task1: {task1.state()}: result: {task1.get()}
                    task2: {task2.state()}: result: {task2.get()}
                    task3: {task3.state()}: result: {task3.get()}
                    """);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(STR."AllSuccess : {Duration.between(start1, Instant.now()).toMillis()}ms");
    }

    static class Weather{
        static Random random = new Random();
        public static String getTempFromA(){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return STR."Temp from A: Temp = {random.nextInt(0, 100)}";
        }
        public static String getTempFromB(){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return STR."Temp from B: Temp = {random.nextInt(0, 100)}";
        }

        public static String getTempFromC(){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return STR."Temp from C: Temp = {random.nextInt(0, 100)}";
        }


    }
}

Output i m getting:

task1: SUCCESS: result : Temp from A: Temp = 57
task2: SUCCESS: result : Temp from B: Temp = 20
task3: SUCCESS: result : Temp from C: Temp = 45

AnySuccess : 57ms
==================
task1: SUCCESS: result: Temp from A: Temp = 78
task2: SUCCESS: result: Temp from B: Temp = 54
task3: SUCCESS: result: Temp from C: Temp = 59

AllSuccess : 18ms

谁能解释这一区别?

成就

问题回答

你的结果表明,所有3项任务都因两项任务而相互隔绝。 由于这些任务每花10米左右的时间,他们在“ShutdownOn Success”的手稿可以停下来。

在休息和暖气之后,你应看到类似的间隔时间,有时一些任务成果是UNAVAILABLE,显示“Shutdownon Success”手递人的预期行为:

for (int i = 0; i < 30; i++) {
    ... as before    
}

请参看<代码>ShutdownOn Success。 一次工作将任务1的睡觉时间改为1 000次,任务2改为100次,使任务1/2在任务3撤离时可能不会完成。 接着,在任务3撤离后,应确认<代码>Any Success已取消任务1/task2:

task1: UNAVAILABLE: result : Not Available
task2: UNAVAILABLE: result : Not Available
task3: SUCCESS: result : Temp from C: Temp = XXXX

I didnt work in subtasks but from your description I see that invoke any thread means: just start a task one of them. Invoke All means that start all of them.

因此,当你们想到其中一项任务时,就开始做一个工作。 另一些则同时援引所有任务。

页: 1 ShutdownOn Success差不多正确,但超过ShutdownOnFailure<>则不完全正确。

what I understand is in ShutdownOnSuccess case if one task get completed rest will be interrupted and in ShutdownOnFailure all task needs to be completed , then shutdown call is made.

这两份文件都解释了差异,并明确了如何处理次塔。 我进一步引用(格式):

ShutdownOnSuccess (invoke any)

页: 1 一旦被抓获,它便将任务范围关闭至不间断的未竟就绪,并提醒任务范围所有人。

ShutdownOnFailure (invoke all)

... captures the exception of the first subtask to fail. Once captured, it shuts down the task scope to interrupt unfinished threads and wakeup the task scope owner.


Performance

在贵问题中分享的执行情况和比较范围类型的业绩。 你们会发现,与更好的基准技术相比,没有什么差别。 例如,在JMH的帮助下,将同一守则基准化如下:

@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000)

results with comparable performance

Benchmark                                               Mode  Cnt      Score     Error  Units
ShutdownSuccessVsShutdownOnFailure.onFailure          sample   10  12252.401 ± 228.142  ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.00    sample       11844.714            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.50    sample       12297.699            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.90    sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.95    sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.99    sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.999   sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p0.9999  sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onFailure:p1.00    sample       12364.808            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess          sample   10  12316.154 ± 105.906  ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.00    sample       12180.259            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.50    sample       12339.642            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.90    sample       12396.685            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.95    sample       12398.363            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.99    sample       12398.363            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.999   sample       12398.363            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p0.9999  sample       12398.363            ms/op
ShutdownSuccessVsShutdownOnFailure.onSuccess:p1.00    sample       12398.363            ms/op

与此相当的原因是每项任务(如果是你的话,整个时间)所花的时间。 如果你将睡觉时间改变为一项任务更高的价值,产出的差别就会更大。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...