How to "mock" the StructuredTaskScope for integration tests where we want to run every task sequentially instead of concurrently

Daniel Andres Pelaez Lopez estigma88 at gmail.com
Wed Mar 26 14:29:04 UTC 2025


I did try to inherit from StructuredTaskScope and create our implementation:

public class SameThread extends StructuredTaskScope<Object> {
    @Override
    public <U> Subtask<U> fork(Callable<? extends U> task) {
        try {
            return new SameThreadTask(task);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

class SameThreadTask<T> implements StructuredTaskScope.Subtask<Object> {
    private Callable<Object> callable;

    public SameThreadTask(Callable<Object> callable) {
        this.callable = callable;
    }

    @Override
    public Callable<?> task() {
        return callable;
    }

    @Override
    public State state() {
        return null;
    }

    @Override
    public Object get() {
        try {
            return callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Throwable exception() {
        return null;
    }
}

However, StructuredTaskScope.Subtask is sealed, so, we cannot inherit from
it

> A ThreadFactory can decorate the
> Runnable to use a Semaphore to limit concurrency and a single permit
> would ensure the subtasks execute sequentially

I will try that, however, seems quite complex anyway.

El mié, 26 mar 2025 a las 3:37, Alan Bateman (<alan.bateman at oracle.com>)
escribió:

> On 25/03/2025 20:35, Daniel Andres Pelaez Lopez wrote:
> >
> > :
> >
> > Challenge:
> >
> > Testing JEP 499: Structured Concurrency (Third Preview) we couldn't
> > find an easy way to do this, perhaps we need to create a new
> > StructuredTaskScope implementation as we do with Executor interface?
> > or should we pass a custom ThreadFactory that only creates one thread?
>
> A new virtual thread is started to execute each subtask. So no
> equivalent of a "caller runs" policy. A ThreadFactory can decorate the
> Runnable to use a Semaphore to limit concurrency and a single permit
> would ensure the subtasks execute sequentially. Would that help what you
> are doing?
>
> -Alan
>


-- 
Daniel Andrés Pelaez López
Master’s Degree in IT Architectures, Universidad de los Andes.
Software Construction Specialist, Universidad de los Andes.
Bachelor's Degree in Computer Sciences, Universidad del Quindio.
e. estigma88 at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20250326/b18ffcb9/attachment.htm>


More information about the loom-dev mailing list