Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion com.avaloq.tools.ddk.xtext.builder/META-INF/MANIFEST.MF
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion com.avaloq.tools.ddk.xtext.builder/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<version>18.0.1-SNAPSHOT</version>
<relativePath>../ddk-parent</relativePath>
</parent>
<version>17.3.4-SNAPSHOT</version>
<version>17.3.5-SNAPSHOT</version>
<groupId>com.avaloq.tools.ddk</groupId>
<artifactId>com.avaloq.tools.ddk.xtext.builder</artifactId>
<packaging>eclipse-plugin</packaging>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -162,9 +165,9 @@ private static boolean isStockUriHandler(final Object uriHandler) {
* Parallel load operation implementation.
* <p>
* 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.
* </p>
*/
@SuppressWarnings("PMD.PublicMemberInNonPublicType") // Public methods needed for subclass access in other packages
Expand All @@ -181,6 +184,13 @@ protected class ParallelLoadOperation implements LoadOperation {
private Collection<URI> 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;
Expand Down Expand Up @@ -227,20 +237,30 @@ public Collection<URI> 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));
}
}
Expand All @@ -256,7 +276,15 @@ public LoadResult next() {
}
Triple<URI, Resource, Throwable> 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();
}
Expand Down Expand Up @@ -323,23 +351,74 @@ public void load(final Collection<URI> uris) {
* </p>
*/
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<URI> 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
@SuppressFBWarnings("AT_STALE_THREAD_WRITE_OF_PRIMITIVE")
public Collection<URI> 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<URI> notStarted = inOrderResults.cancel();
List<URI> 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;
}
Expand Down Expand Up @@ -454,54 +533,15 @@ private static BlockingQueue<Triple<URI, Resource, Throwable>> 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<URI> workload;
private final int window;
private final ReentrantLock lock = new ReentrantLock();
private final Condition resultAvailable = lock.newCondition();
private final NavigableMap<Integer, Triple<URI, Resource, Throwable>> 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<URI> 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.
*
Expand All @@ -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<URI, Resource, Throwable> result) {
if (!cancelled) {
results.put(index, result);
notifyAll();
void put(final int index, final Triple<URI, Resource, Throwable> result) {
lock.lock();
try {
if (!cancelled) {
results.put(index, result);
resultAvailable.signal();
}
} finally {
lock.unlock();
}
}

Expand All @@ -526,34 +571,33 @@ synchronized void put(final int index, final Triple<URI, Resource, Throwable> re
* @throws InterruptedException
* if the thread is interrupted while waiting
*/
synchronized Triple<URI, Resource, Throwable> 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<URI, Resource, Throwable> 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<URI> cancel() {
cancelled = true;
results.clear();
notifyAll();
List<URI> 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;
}
}

Expand Down
Loading