diff --git a/com.avaloq.tools.ddk.xtext.builder/META-INF/MANIFEST.MF b/com.avaloq.tools.ddk.xtext.builder/META-INF/MANIFEST.MF
index 5e7da74236..8de45ca01f 100644
--- a/com.avaloq.tools.ddk.xtext.builder/META-INF/MANIFEST.MF
+++ b/com.avaloq.tools.ddk.xtext.builder/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: com.avaloq.tools.ddk.xtext.builder
Bundle-SymbolicName: com.avaloq.tools.ddk.xtext.builder;singleton:=true
-Bundle-Version: 17.3.4.qualifier
+Bundle-Version: 17.3.5.qualifier
Bundle-Vendor: Avaloq Group AG
Require-Bundle: org.eclipse.xtext.builder,
org.eclipse.xtext.ui,
diff --git a/com.avaloq.tools.ddk.xtext.builder/pom.xml b/com.avaloq.tools.ddk.xtext.builder/pom.xml
index 415f47ad0f..29530fda41 100644
--- a/com.avaloq.tools.ddk.xtext.builder/pom.xml
+++ b/com.avaloq.tools.ddk.xtext.builder/pom.xml
@@ -6,7 +6,7 @@
18.0.1-SNAPSHOT
../ddk-parent
- 17.3.4-SNAPSHOT
+ 17.3.5-SNAPSHOT
com.avaloq.tools.ddk
com.avaloq.tools.ddk.xtext.builder
eclipse-plugin
diff --git a/com.avaloq.tools.ddk.xtext.builder/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoader.java b/com.avaloq.tools.ddk.xtext.builder/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoader.java
index 8d828066b6..d208b1d1ff 100644
--- a/com.avaloq.tools.ddk.xtext.builder/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoader.java
+++ b/com.avaloq.tools.ddk.xtext.builder/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoader.java
@@ -13,7 +13,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
@@ -25,9 +24,13 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -162,9 +165,9 @@ private static boolean isStockUriHandler(final Object uriHandler) {
* Parallel load operation implementation.
*
* The resources scheduled by {@link #startThreads()} are handed out in the order of the workload, which the builder sorts to build the resources a resource
- * depends on before it, as far as they are loaded: a result is never held back for a resource before it which is still being loaded. Only resources within a
- * window of positions after the number of results handed out are loaded, which bounds the loaded resources not handed out yet, as the result queue does
- * otherwise. Subclasses scheduling the loads themselves get the results as they come.
+ * depends on before it, as far as they are loaded: a result is never held back for a resource before it which is still being loaded. Only the loads within a
+ * window of positions after the number of results handed out are submitted to the executor, which bounds the loaded resources not handed out yet, as the
+ * result queue does otherwise; each result handed out submits the next load. Subclasses scheduling the loads themselves get the results as they come.
*
*/
@SuppressWarnings("PMD.PublicMemberInNonPublicType") // Public methods needed for subclass access in other packages
@@ -181,6 +184,13 @@ protected class ParallelLoadOperation implements LoadOperation {
private Collection workload;
/** The results in workload order, {@code null} unless the loads were scheduled by {@link #startThreads()}. */
private InOrderResults inOrderResults;
+ /** Guards {@link #jobs}, {@link #submitted} and {@link #cancelled} against a {@link #cancel()} from another thread; the workers never take it. */
+ private final Object submissionLock = new Object();
+ /** The loads scheduled by {@link #startThreads()}, in workload order. */
+ private ResourceLoadJob[] jobs;
+ /** The number of loads scheduled by {@link #startThreads()} that were submitted to the executor. */
+ private int submitted;
+ private boolean cancelled;
public ParallelLoadOperation(final ResourceSet parent, final IProject project) {
this.parent = parent;
@@ -227,20 +237,30 @@ public Collection getWorkload() {
}
/**
- * Resource load job to load a single resource.
+ * Resource load job to load a single resource. Either a worker starts it or {@link #cancel()} drops it, whichever claims it first.
*/
private class ResourceLoadJob implements Runnable {
private final URI uri;
private final int index;
+ private final AtomicBoolean claimed = new AtomicBoolean();
ResourceLoadJob(final URI uri, final int index) {
this.uri = uri;
this.index = index;
}
+ /**
+ * Claims this job, so that it is either started or dropped, but not both.
+ *
+ * @return {@code true} if the caller claimed it, {@code false} if it was claimed before
+ */
+ boolean claim() {
+ return claimed.compareAndSet(false, true);
+ }
+
@Override
public void run() {
- if (inOrderResults.awaitTurn(index)) {
+ if (claim()) {
inOrderResults.put(index, load(uri));
}
}
@@ -256,7 +276,15 @@ public LoadResult next() {
}
Triple result = null;
try {
- result = inOrderResults != null ? inOrderResults.take(waitTime) : resourceQueue.poll(waitTime, TimeUnit.MILLISECONDS);
+ if (inOrderResults != null) {
+ result = inOrderResults.take(waitTime);
+ if (result != null) {
+ // a result handed out moves the window by one position
+ submitLoads(1);
+ }
+ } else {
+ result = resourceQueue.poll(waitTime, TimeUnit.MILLISECONDS);
+ }
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
@@ -323,14 +351,56 @@ public void load(final Collection uris) {
*
*/
protected void startThreads() {
+ synchronized (submissionLock) {
+ jobs = new ResourceLoadJob[workload.size()];
+ int index = 0;
+ for (URI uri : workload) {
+ jobs[index] = new ResourceLoadJob(uri, index);
+ index++;
+ }
+ }
+ inOrderResults = new InOrderResults();
+ if (workload.isEmpty()) {
+ executor.shutdown();
+ }
// the positions are taken by the loads in progress as well as by the results not handed out yet: with twice as many positions as threads, the threads
// keep loading ahead while the builder processes a resource, so that the builder does not wait for a load each time it gets ahead
- List uris = List.copyOf(workload);
- inOrderResults = new InOrderResults(uris, queueSize < 0 ? Integer.MAX_VALUE : 2 * getNThreads() + queueSize);
- for (int index = 0; index < uris.size(); index++) {
- executor.execute(new ResourceLoadJob(uris.get(index), index));
+ submitLoads(queueSize < 0 ? Integer.MAX_VALUE : 2 * getNThreads() + queueSize);
+ }
+
+ /**
+ * Submits the next loads scheduled by {@link #startThreads()} to the executor, unless the operation was cancelled, and shuts the executor down once the
+ * last one is submitted.
+ *
+ * @param count
+ * the maximum number of loads to submit
+ */
+ private void submitLoads(final int count) {
+ final ResourceLoadJob[] scheduled;
+ final int from;
+ final int to;
+ synchronized (submissionLock) {
+ if (cancelled) {
+ return;
+ }
+ scheduled = jobs;
+ from = submitted;
+ to = (int) Math.min(scheduled.length, (long) from + count);
+ submitted = to;
+ }
+ if (from == to) {
+ return;
+ }
+ try {
+ for (int index = from; index < to; index++) {
+ executor.execute(scheduled[index]);
+ }
+ if (to == scheduled.length) {
+ executor.shutdown();
+ }
+ } catch (RejectedExecutionException e) {
+ // cancelled meanwhile: cancel() claimed the jobs not started and reports them
}
- executor.shutdown();
}
@Override
@@ -338,8 +408,17 @@ protected void startThreads() {
public Collection cancel() {
toProcess = 0;
if (inOrderResults != null) {
- // no load may start any more before the jobs are dropped, so that a job a thread has just taken cannot slip through
- Collection notStarted = inOrderResults.cancel();
+ List notStarted = Lists.newArrayList();
+ synchronized (submissionLock) {
+ cancelled = true;
+ // a job no worker has claimed, whether not submitted yet, still queued or just taken from the queue, never starts once claimed here
+ for (ResourceLoadJob job : jobs) {
+ if (job.claim()) {
+ notStarted.add(job.uri);
+ }
+ }
+ }
+ inOrderResults.cancel();
executor.shutdownNow();
return notStarted;
}
@@ -454,54 +533,15 @@ private static BlockingQueue> createResultQueue
/**
* Hands out the load results in the order of their positions in the workload, as far as they are loaded: the result with the lowest position is handed out,
- * without waiting for a result with a lower position still being loaded. A load may start only within a window of positions after the number of results
- * handed out. The loads are started in workload order, so a load can always start while no result is available.
+ * without waiting for a result with a lower position still being loaded. Only the thread taking the results waits, so a result put wakes just that thread.
*/
private static final class InOrderResults {
- private final List workload;
- private final int window;
+ private final ReentrantLock lock = new ReentrantLock();
+ private final Condition resultAvailable = lock.newCondition();
private final NavigableMap> results = new TreeMap<>();
- private final BitSet started = new BitSet();
- private int handedOut;
private boolean cancelled;
- /**
- * Creates a new instance.
- *
- * @param workload
- * the URIs to load, must not be {@code null}
- * @param window
- * the number of positions after the number of results handed out that may be loaded, at least 1
- */
- InOrderResults(final List workload, final int window) {
- this.workload = workload;
- this.window = window;
- }
-
- /**
- * Waits until the load at the given position may start.
- *
- * @param index
- * the position in the workload
- * @return {@code true} if the load may start, {@code false} if the operation was cancelled or the thread interrupted
- */
- synchronized boolean awaitTurn(final int index) {
- try {
- while (!cancelled && (long) index - handedOut >= window) {
- wait();
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return false;
- }
- if (cancelled) {
- return false;
- }
- started.set(index);
- return true;
- }
-
/**
* Publishes the result at the given position.
*
@@ -510,10 +550,15 @@ synchronized boolean awaitTurn(final int index) {
* @param result
* the load result, must not be {@code null}
*/
- synchronized void put(final int index, final Triple result) {
- if (!cancelled) {
- results.put(index, result);
- notifyAll();
+ void put(final int index, final Triple result) {
+ lock.lock();
+ try {
+ if (!cancelled) {
+ results.put(index, result);
+ resultAvailable.signal();
+ }
+ } finally {
+ lock.unlock();
}
}
@@ -526,34 +571,33 @@ synchronized void put(final int index, final Triple re
* @throws InterruptedException
* if the thread is interrupted while waiting
*/
- synchronized Triple take(final long timeoutMillis) throws InterruptedException {
- long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
- while (results.isEmpty()) {
- long remaining = deadline - System.nanoTime();
- if (remaining <= 0) {
- return null;
+ Triple take(final long timeoutMillis) throws InterruptedException {
+ lock.lock();
+ try {
+ long remaining = TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+ while (results.isEmpty()) {
+ if (remaining <= 0) {
+ return null;
+ }
+ remaining = resultAvailable.awaitNanos(remaining);
}
- TimeUnit.NANOSECONDS.timedWait(this, remaining);
+ return results.pollFirstEntry().getValue();
+ } finally {
+ lock.unlock();
}
- handedOut++;
- notifyAll();
- return results.pollFirstEntry().getValue();
}
/**
- * Cancels the loads which have not started yet; no load starts afterwards.
- *
- * @return the URIs of the loads which did not start, never {@code null}
+ * Drops the results not taken yet, and those put afterwards.
*/
- synchronized Collection cancel() {
- cancelled = true;
- results.clear();
- notifyAll();
- List notStarted = Lists.newArrayList();
- for (int index = started.nextClearBit(0); index < workload.size(); index = started.nextClearBit(index + 1)) {
- notStarted.add(workload.get(index));
+ void cancel() {
+ lock.lock();
+ try {
+ cancelled = true;
+ results.clear();
+ } finally {
+ lock.unlock();
}
- return notStarted;
}
}
diff --git a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoaderTest.java b/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoaderTest.java
index 4091b8be1b..7d548741b4 100644
--- a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoaderTest.java
+++ b/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/builder/resourceloader/ParallelResourceLoaderTest.java
@@ -30,6 +30,7 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
@@ -79,6 +80,7 @@ public class ParallelResourceLoaderTest {
private static final int[] QUEUE_SIZES = {-1, 0};
private static final String OTHER_OPTION = "other.option";
private static final String LATE_OPTION = "late.option";
+ private static final String NO_LOAD_AFTER_CANCEL = "no load may start after cancel";
/** The executors of the load operations created by {@link #load}, to wait until their loads end. */
private static final Map EXECUTORS = Maps.newConcurrentMap();
@@ -240,12 +242,99 @@ public void loadsAheadOfTheResultsHandedOutAreBounded() {
assertEquals(Set.copyOf(uris.subList(5, 10)), Set.copyOf(operation.cancel()), "cancel must return the resources not loaded");
Uninterruptibles.sleepUninterruptibly(SETTLE_MILLIS, TimeUnit.MILLISECONDS);
- assertEquals(5, loaded.size(), "no load may start after cancel");
+ assertEquals(5, loaded.size(), NO_LOAD_AFTER_CANCEL);
} finally {
operation.cancel();
}
}
+ @Test
+ public void onlyTheLoadsWithinTheWindowAreSubmitted() throws InterruptedException {
+ List uris = uris(5);
+ CountDownLatch firstStarted = new CountDownLatch(1);
+ CountDownLatch firstReleased = new CountDownLatch(1);
+ // one thread and a synchronous hand-off: two positions after the results handed out
+ LoadOperation operation = load(uris, 0, 1, GENEROUS_TIMEOUT_MILLIS, uri -> {
+ if (uris.get(0).equals(uri)) {
+ firstStarted.countDown();
+ Uninterruptibles.awaitUninterruptibly(firstReleased);
+ }
+ return new ResourceImpl(uri);
+ });
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) EXECUTORS.get(operation);
+ try {
+ assertAwaited(firstStarted);
+ assertEquals(1, executor.getQueue().size(), "only the window must be submitted, so that no thread waits for its turn");
+ assertFalse(executor.isShutdown(), "the executor must take the loads submitted as results are handed out");
+
+ firstReleased.countDown();
+ List handedOut = new ArrayList<>();
+ while (operation.hasNext()) {
+ handedOut.add(operation.next().getResource().getURI());
+ }
+ assertEquals(uris, handedOut);
+ assertTrue(executor.awaitTermination(GENEROUS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS), "the executor must be shut down once the last load is submitted");
+ } finally {
+ firstReleased.countDown();
+ operation.cancel();
+ }
+ }
+
+ @Test
+ public void loadsStayWithinTheWindowThroughoutTheOperation() {
+ List uris = uris(40);
+ Set taken = ConcurrentHashMap.newKeySet();
+ List violations = Collections.synchronizedList(new ArrayList<>());
+ // two threads and a synchronous hand-off: four positions after the results handed out
+ int window = 4;
+ LoadOperation operation = load(uris, 0, 2, GENEROUS_TIMEOUT_MILLIS, uri -> {
+ int index = uris.indexOf(uri);
+ int handedOut = taken.size();
+ // the next() in progress may already have moved the window, before the test counts its result
+ if (index >= handedOut + 1 + window) {
+ violations.add(index + " started after " + handedOut + " results");
+ }
+ // the threads finish out of workload order
+ Uninterruptibles.sleepUninterruptibly(index % 3, TimeUnit.MILLISECONDS);
+ return new ResourceImpl(uri);
+ });
+ try {
+ while (operation.hasNext()) {
+ taken.add(operation.next().getResource().getURI());
+ }
+ assertEquals(Set.copyOf(uris), taken, "every resource must be handed out once");
+ assertEquals(List.of(), violations, "no load may start beyond the window");
+ } finally {
+ operation.cancel();
+ }
+ }
+
+ @Test
+ public void cancelReturnsExactlyTheLoadsNotStarted() throws InterruptedException {
+ List uris = uris(5);
+ Set loaded = ConcurrentHashMap.newKeySet();
+ CountDownLatch firstStarted = new CountDownLatch(1);
+ CountDownLatch firstReleased = new CountDownLatch(1);
+ // one thread and a synchronous hand-off: the second load is queued in the executor, the others are not submitted yet
+ LoadOperation operation = load(uris, 0, 1, GENEROUS_TIMEOUT_MILLIS, uri -> {
+ loaded.add(uri);
+ firstStarted.countDown();
+ Uninterruptibles.awaitUninterruptibly(firstReleased);
+ return new ResourceImpl(uri);
+ });
+ ExecutorService executor = EXECUTORS.get(operation);
+ try {
+ assertAwaited(firstStarted);
+ assertEquals(uris.subList(1, 5), List.copyOf(operation.cancel()), "cancel must return the queued and the unsubmitted loads, in workload order");
+ firstReleased.countDown();
+ assertTrue(executor.awaitTermination(GENEROUS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
+ assertEquals(Set.of(uris.get(0)), loaded, NO_LOAD_AFTER_CANCEL);
+ } finally {
+ firstReleased.countDown();
+ operation.cancel();
+ }
+ }
+
@Test
public void workerKeepsItsOwnUriHandlerWhenParentUsesTheStockHandler() {
ResourceSet parent = new XtextResourceSet();