Question about StructuredTaskScope.joinUntil(Instant)

Werner Randelshofer werner.randelshofer at fibermail.ch
Tue Jun 11 15:32:59 UTC 2024


I have solved my problem. :-)

I have now implemented a subclass of StructuredTaskScope, which allows to specify a deadline in System.nanoTime() units.
With this design, the deadline is independent from external resources (like NTP time servers) over which the Java process has no control. 

See code below.

With best regards,
Werner



package org.example.structuredconcurrency;

import java.time.Duration;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeoutException;

/**
 * A {@link StructuredTaskScope} that supports a deadline given in {@link System#nanoTime()}.
 *
 * @param <T> the type of the structured task scope
 */
public class StructuredTaskScopeNanoTime<T> extends StructuredTaskScope<T> {

    /**
     * Creates an unnamed structured task scope that creates virtual threads. The task
     * scope is owned by the current thread.
     */
    public StructuredTaskScopeNanoTime() {
    }

    /**
     * Creates a structured task scope with the given name and thread factory.
     *
     * @param name    the name of the task scope, can be null
     * @param factory the thread factory
     */
    public StructuredTaskScopeNanoTime(String name, ThreadFactory factory) {
        super(name, factory);
    }

    /**
     * Wait for all subtasks started in this task scope to finish or the task scope to
     * shut down, up to the given deadline.
     *
     * @param deadlineNanoTime the deadline given in {@link System#nanoTime()} units
     * @return this task scope
     * @throws IllegalStateException if this task scope is closed
     * @throws WrongThreadException  if the current thread is not the task scope owner
     * @throws InterruptedException  if interrupted while waiting
     * @throws TimeoutException      if the deadline is reached while waiting
     */
    public StructuredTaskScopeNanoTime<T> joinUntilNanoTime(long deadlineNanoTime) throws InterruptedException, TimeoutException {
        fork(() -> {
            Thread.sleep(Duration.ofNanos(deadlineNanoTime - System.nanoTime()));
            shutdown();
            return null;
        });
        join();
        return this;
    }
}



More information about the loom-dev mailing list