// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import jdk.incubator.concurrent.StructuredTaskScope;

public class SC19 {
    public static int sum(int[] a, int start, int end) {
        int res = 0;
        for(int i = start; i <= end; i++) {
            res += a[i];
            try {
                Thread.sleep(10); // simulate work taking time
            } catch(InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        return res;
    }
    private static final int SIZ = 1000;
    private static final int NTASK = 10;
    private static final int TASKSIZ = SIZ / NTASK;
    public static void main(String[] args) throws InterruptedException {
        final int[] a = new int[SIZ];
        for(int i = 0; i < a.length; i++) {
            a[i] = i + 1;
        }
        try(StructuredTaskScope scope = new StructuredTaskScope.ShutdownOnFailure()) {
            List<Future<Integer>> flst = new ArrayList<Future<Integer>>();
            for(int i = 0; i < NTASK; i++) {
                final int start = i * TASKSIZ;
                final int end = start + TASKSIZ - 1;
                flst.add(scope.fork(() -> sum(a, start, end)));
            }
            scope.join();
            int sum = flst.stream().mapToInt(f -> f.resultNow()).sum();
            System.out.println(sum);
        }
    }
}
