applies concurrency fixes

This commit is contained in:
eyck committed 2026-11-20 22:31:48 +01:00
1 parent 42e0d83403
commit 28eb1b673e
56 files changed
+1462 -372

No files matched your search

@@ -65,6 +65,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
this.sources = List.copyOf(normalized);
}
@Override public List<IWaveform> getReadSources() { return sources.stream().map(SourceBit::waveform).toList(); }
public List<SourceBit> getSources() { return sources; }
@Override public String getFullName() { return identifier; }
@Override public String getDisplayName() { return getName(); }
@@ -95,6 +96,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
}
BitValue[] value = new BitValue[getWidth()];
for (int i = 0; i < value.length; i++) {
ReadCancellation.check();
EventEntry entry = inputs().get(i).floorEntry(time);
value[i] = BitValue.X;
if (entry != null && entry.events != null && entry.events.length > 0) {
@@ -112,6 +114,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
private Long candidate(long time, boolean forward, boolean inclusive) {
Long result = null;
for (IEventList input : inputs()) {
ReadCancellation.check();
EventEntry entry = forward ? (inclusive ? input.ceilingEntry(time) : input.higherEntry(time))
: (inclusive ? input.floorEntry(time) : input.lowerEntry(time));
if (entry != null && (result == null || (forward
@@ -138,7 +141,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
break;
}
if (changed(next)) break;
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
ReadCancellation.check();
next = candidate(next, forward, false);
}
synchronized (positions) { positions.put(query, next); }
@@ -22,10 +22,10 @@ import java.util.List;
public class HierNode implements IHierNode {
/** The name. */
protected String name;
protected volatile String name;
/** The parent. */
protected IHierNode parent = null;
protected volatile IHierNode parent = null;
/** The childs. */
protected List<IHierNode> childNodes = Collections.synchronizedList(new ArrayList<>());
@@ -139,7 +139,7 @@ public class HierNode implements IHierNode {
*/
@Override
public List<IHierNode> getChildNodes() {
return Collections.unmodifiableList(childNodes);
synchronized (childNodes) { return List.copyOf(childNodes); }
}
/**
@@ -149,9 +149,11 @@ public class HierNode implements IHierNode {
*/
@Override
public void addChild(IHierNode child) {
if (!childNodes.contains(child)) {
childNodes.add(child);
child.setParent(this);
synchronized (childNodes) {
if (!childNodes.contains(child)) {
child.setParent(this);
childNodes.add(child);
}
}
}
@@ -19,6 +19,13 @@ package com.minres.scviewer.database;
*/
public interface IWaveform extends IHierNode {
/** Recorded inputs used to coordinate derived reads with database closure. */
default java.util.List<IWaveform> getReadSources() { return java.util.List.of(this); }
/** Signal metadata; real-valued loaders override this without reading events. */
default boolean isBitVector() { return getType() == WaveformType.SIGNAL && getWidth() > 0; }
/** User-facing label; derived waveforms may have a separate persistent identity. */
default String getDisplayName() { return getFullName(); }
@@ -10,31 +10,45 @@
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.concurrent.CancellationException;
import java.util.function.Supplier;
/** Publishes one complete value, including empty values, and preserves loading failures. */
/** Single-flight lazy initialization. Waiters can cancel without cancelling the owner. */
public final class LazyValue<T> {
private enum State { UNLOADED, LOADING, LOADED, FAILED }
private State state = State.UNLOADED;
private Thread owner;
private T value;
private Throwable failure;
public synchronized T get(Supplier<T> supplier) {
if (state == State.LOADED) return value;
if (state == State.FAILED) {
if (failure instanceof Error) throw (Error) failure;
throw (RuntimeException) failure;
public T get(Supplier<T> supplier) {
synchronized (this) {
while (state == State.LOADING) {
if (owner == Thread.currentThread()) throw new IllegalStateException("Recursive lazy loading");
ReadCancellation.check();
try { wait(50); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CancellationException(); }
}
ReadCancellation.check();
if (state == State.LOADED) return value;
if (state == State.FAILED) {
if (failure instanceof Error error) throw error;
throw (RuntimeException) failure;
}
owner = Thread.currentThread();
state = State.LOADING;
}
if (state == State.LOADING) throw new IllegalStateException("Recursive lazy loading");
state = State.LOADING;
try {
T loaded = supplier.get();
value = loaded;
state = State.LOADED;
synchronized (this) { value = loaded; state = State.LOADED; owner = null; notifyAll(); }
return loaded;
} catch (RuntimeException | Error e) {
failure = e;
state = State.FAILED;
synchronized (this) {
if (e instanceof CancellationException) state = State.UNLOADED;
else { failure = e; state = State.FAILED; }
owner = null;
notifyAll();
}
throw e;
}
}
@@ -0,0 +1,32 @@
/*******************************************************************************
* Copyright (c) 2026 MINRES Technologies GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MINRES Technologies GmbH - initial API and implementation
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
/** Cancellation context for nested lazy reads without depending on Eclipse jobs. */
public final class ReadCancellation {
private static final ThreadLocal<BooleanSupplier> CURRENT = new ThreadLocal<>();
private ReadCancellation() { }
public static void check() {
BooleanSupplier cancelled = CURRENT.get();
if (Thread.currentThread().isInterrupted() || (cancelled != null && cancelled.getAsBoolean()))
throw new CancellationException();
}
public static <T> T with(BooleanSupplier cancelled, Supplier<T> query) {
BooleanSupplier previous = CURRENT.get();
CURRENT.set(() -> cancelled.getAsBoolean() || (previous != null && previous.getAsBoolean()));
try { check(); return query.get(); }
finally { if (previous == null) CURRENT.remove(); else CURRENT.set(previous); }
}
}
@@ -10,7 +10,7 @@
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* A factory for creating RelationType objects.
@@ -24,14 +24,7 @@ public class RelationTypeFactory {
* @return the relation type
*/
public static RelationType create(String name) {
if (registry.containsKey(name)) {
return registry.get(name);
} else {
RelationType relType = new RelationType(name);
registry.put(name, relType);
return relType;
}
return registry.computeIfAbsent(name, RelationType::new);
}
/**
@@ -41,6 +34,6 @@ public class RelationTypeFactory {
}
/** The registry. */
private static HashMap<String, RelationType> registry = new HashMap<>();
private static ConcurrentHashMap<String, RelationType> registry = new ConcurrentHashMap<>();
}
@@ -0,0 +1,89 @@
/*******************************************************************************
* Copyright (c) 2026 MINRES Technologies GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MINRES Technologies GmbH - initial API and implementation
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/** Coordinates background consumers with database closure. Owners are weakly keyed:
* stale waveform references retain a closed scope and cannot reopen a recording.
*/
public final class WaveformAccess {
private static final Map<IWaveform, Scope> OWNERS = new WeakHashMap<>();
private static final AtomicLong IDS = new AtomicLong();
private WaveformAccess() { }
public static final class Scope {
private final long id = IDS.incrementAndGet();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private volatile boolean closing;
public void register(Collection<IWaveform> waveforms) {
synchronized (OWNERS) { for (IWaveform waveform : waveforms) OWNERS.put(waveform, this); }
}
/** Must run on a worker: waits for existing leases, rejecting new ones. */
public void close(Runnable cleanup) {
closing = true;
lock.writeLock().lock();
try { cleanup.run(); }
finally { lock.writeLock().unlock(); }
}
private void acquire() {
try {
while (!closing) {
ReadCancellation.check();
if (lock.readLock().tryLock(50, TimeUnit.MILLISECONDS)) {
if (!closing) return;
lock.readLock().unlock();
}
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
throw new CancellationException("Database is closing");
}
}
public static <T> T read(IWaveform waveform, Supplier<T> query) {
return read(waveform == null ? List.of() : List.of(waveform), query);
}
public static <T> T read(Collection<IWaveform> waveforms, Supplier<T> query) {
Map<Scope, Boolean> scopes = new IdentityHashMap<>();
synchronized (OWNERS) {
for (IWaveform waveform : waveforms) collect(waveform, scopes);
}
List<Scope> ordered = new ArrayList<>(scopes.keySet());
ordered.sort(Comparator.comparingLong(scope -> scope.id));
int acquired = 0;
try {
for (Scope scope : ordered) { scope.acquire(); acquired++; }
ReadCancellation.check();
return query.get();
} finally {
for (int i = acquired - 1; i >= 0; i--) ordered.get(i).lock.readLock().unlock();
}
}
private static void collect(IWaveform waveform, Map<Scope, Boolean> scopes) {
Scope scope = OWNERS.get(waveform);
if (scope != null) scopes.put(scope, Boolean.TRUE);
else {
List<IWaveform> sources = waveform.getReadSources();
if (sources != null) for (IWaveform source : sources) if (source != null && source != waveform) collect(source, scopes);
}
}
}
@@ -17,6 +17,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.List;
import java.util.Map;
@@ -30,6 +31,7 @@ import com.minres.scviewer.database.IWaveformDb;
import com.minres.scviewer.database.IWaveformDbLoader;
import com.minres.scviewer.database.IWaveformDbLoaderFactory;
import com.minres.scviewer.database.RelationType;
import com.minres.scviewer.database.WaveformAccess;
/**
* The Class WaveformDb.
@@ -39,6 +41,9 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
/** The loaders. */
private static final CopyOnWriteArrayList<IWaveformDbLoaderFactory> loaderFactories = new CopyOnWriteArrayList<>();
private final ReentrantLock lifecycle = new ReentrantLock();
private WaveformAccess.Scope readScope = new WaveformAccess.Scope();
private List<IWaveformDbLoader> activeLoader = new ArrayList<>();
/** The loaded. */
private volatile boolean loaded;
@@ -122,9 +127,10 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
public boolean load(File inp) {
List<PropertyChangeEvent> notifications = new ArrayList<>();
boolean result;
synchronized (this) {
result = loadLocked(inp, notifications);
}
lifecycle.lock();
try {
synchronized (this) { result = loadLocked(inp, notifications); }
} finally { lifecycle.unlock(); }
// A listener may wait for the UI, which in turn may need close().
// Never invoke external listeners while holding the database lock.
notifications.forEach(pcs::firePropertyChange);
@@ -132,6 +138,7 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
}
private boolean loadLocked(File inp, List<PropertyChangeEvent> notifications) {
if (activeLoader.isEmpty()) readScope = new WaveformAccess.Scope();
for (IWaveformDbLoaderFactory factory : getLoaders()) {
if (!factory.canLoad(inp)) continue;
IWaveformDbLoader loader = factory.getLoader();
@@ -161,6 +168,7 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
for (PropertyChangeEvent event : pending) applyWaveform(event);
if (!pending.isEmpty()) addWaveformNotifications(notifications);
}
readScope.register(getAllWaves());
loaded = true;
notifications.add(new PropertyChangeEvent(this, IHierNode.LOADING_FINISHED, null, Boolean.TRUE));
return true;
@@ -170,7 +178,13 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
}
@Override
public synchronized void close() {
public void close() {
lifecycle.lock();
try { readScope.close(this::closeLocked); }
finally { lifecycle.unlock(); }
}
private synchronized void closeLocked() {
for (IWaveformDbLoader loader : activeLoader) {
try { loader.dispose(); }
catch (RuntimeException e) { LOG.warn("Cannot dispose database loader", e); }
@@ -264,8 +278,8 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
* @return the all relation types
*/
@Override
public List<RelationType> getAllRelationTypes() {
return relationTypes;
public synchronized List<RelationType> getAllRelationTypes() {
return List.copyOf(relationTypes);
}
}
@@ -27,9 +27,11 @@ public final class TransactionLists {
public static List<ITx> fromEvents(IEventList events, BooleanSupplier cancelled) {
List<ITx> transactions = new ArrayList<>();
for (EventEntry entry : events.entrySet()) {
com.minres.scviewer.database.ReadCancellation.check();
if (cancelled.getAsBoolean()) throw new java.util.concurrent.CancellationException();
if (entry.events == null) continue;
for (IEvent event : entry.events) {
com.minres.scviewer.database.ReadCancellation.check();
if (cancelled.getAsBoolean()) throw new java.util.concurrent.CancellationException();
if (event instanceof ITxEvent tx && (event.getKind() == EventKind.BEGIN || event.getKind() == EventKind.SINGLE))
transactions.add(tx.getTransaction());
@@ -40,7 +42,8 @@ public final class TransactionLists {
public static List<ITx> sorted(java.util.Collection<ITx> transactions) {
List<ITx> sorted = new ArrayList<>(transactions);
sorted.sort(Comparator.comparingLong(ITx::getBeginTime).thenComparingLong(ITx::getId));
Comparator<ITx> order = Comparator.comparingLong(ITx::getBeginTime).thenComparingLong(ITx::getId);
sorted.sort((left, right) -> { com.minres.scviewer.database.ReadCancellation.check(); return order.compare(left, right); });
return List.copyOf(sorted);
}
}
@@ -26,6 +26,7 @@ public final class TxIntervalIndex {
final Node left, right;
Node(List<ITxEvent> events, int from, int to) {
com.minres.scviewer.database.ReadCancellation.check();
int mid = (from + to) >>> 1;
event = events.get(mid);
ITx tx = event.getTransaction();
@@ -52,10 +53,12 @@ public final class TxIntervalIndex {
public TxIntervalIndex(IEventList events) {
List<ITxEvent> starts = new ArrayList<>();
for (EventEntry entry : events)
for (EventEntry entry : events) {
com.minres.scviewer.database.ReadCancellation.check();
for (IEvent event : entry.events)
if (event instanceof ITxEvent && event.getKind() != EventKind.END)
starts.add((ITxEvent) event);
}
// EventList already orders buckets by timestamp, including same-time starts.
root = starts.isEmpty() ? null : new Node(starts, 0, starts.size());
}