Business policy inside a StructuredTaskScope

David david.vlijmincx at gmail.com
Mon Sep 11 21:07:59 UTC 2023


Hi,

I have a question about where the business logic / shutdown policy is
supposed to be when you extend from a StructuredTaskScope. Looking at
online examples it seems like the business logic is supposed to be in the
handleComplete method of a class that extends StructuredTaskScope, but is
this not too far away from the place it is being used?

Currently, I am using the following scope as it keeps the shutdown policy
closer to where the scope is used in my code, but I do not know if this is
the correct way of creating your own scopes.

class TriggerScope<T> extends StructuredTaskScope<T> {

    final private Function<StructuredTaskScope.Subtask<? extends T>,
Boolean> trigger;

    TriggerScope(Function<StructuredTaskScope.Subtask<? extends T>,
Boolean> trigger) {
        this.trigger = trigger;
    }

    @Override
    protected void handleComplete(Subtask<? extends T> subtask) {
        if (trigger.apply(subtask)) {
            shutdown();
        }
    }
}

The above scope allows me to implement a new scope like below:

public static void main(String[] args) throws InterruptedException {

    Main main = new Main();

    try (var scope = new TriggerScope<Product>(main::trigger)) {

        StructuredTaskScope.Subtask<Product> fork = scope.fork(() ->
new Product(50));
        StructuredTaskScope.Subtask<Product> fork1 = scope.fork(() ->
new Product(100));
        StructuredTaskScope.Subtask<Product> fork2 = scope.fork(() ->
new Product(150));

        scope.join();
    }

}

private boolean trigger(StructuredTaskScope.Subtask<? extends Product>
subtask) {
    if (Subtask.State.SUCCESS.equals(subtask.state()) &&
subtask.get().price() > 50 && subtask.get().price() < 150){
        System.out.println("result: " + subtask.get().price());
        return true;
    }
    return false;
}


In my opinion, this way is more convenient, but is this still a correct
implementation or does this deviate too much from the original idea of
creating a scope in its own class?

Looking forward to hearing your thoughts.

Kind regards,
David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230911/586c3976/attachment.htm>


More information about the loom-dev mailing list