修复异步取消并发与延迟事件

This commit is contained in:
张家训
2026-08-01 17:44:56 +08:00
parent 7867304e07
commit 550dbd3b55
4 changed files with 267 additions and 31 deletions
@@ -15,11 +15,14 @@ public final class AsyncOperationController<T> {
private final Executor executor;
private final Consumer<Runnable> uiDispatcher;
private final Object transitionLock = new Object();
private final OperationStateMachine stateMachine = new OperationStateMachine();
private final AtomicBoolean cancellationRequested = new AtomicBoolean();
private final ReadOnlyObjectWrapper<OperationSnapshot> snapshot =
new ReadOnlyObjectWrapper<>(OperationSnapshot.idle());
private final ReadOnlyBooleanWrapper running = new ReadOnlyBooleanWrapper(false);
private long nextGeneration;
private long activeGeneration;
public AsyncOperationController(Executor executor, Consumer<Runnable> uiDispatcher) {
this.executor = Objects.requireNonNull(executor, "executor");
@@ -33,49 +36,42 @@ public final class AsyncOperationController<T> {
public void start(String runningMessage, OperationTask<T> task,
Consumer<T> onSuccess, Consumer<Throwable> onFailure) {
Objects.requireNonNull(task, "task");
if (running.get()) {
throw new IllegalStateException("Operation is already running");
long generation;
synchronized (transitionLock) {
if (running.get()) {
throw new IllegalStateException("Operation is already running");
}
generation = prepareStart(runningMessage);
}
prepareStart(runningMessage);
executor.execute(() -> {
OperationContext context = new OperationContext(
(message, progress) -> dispatchSnapshot(
() -> stateMachine.progress(message, progress)),
(message, progress) -> dispatchProgress(
generation, message, progress),
cancellationRequested::get);
try {
T result = task.execute(context);
uiDispatcher.accept(() -> {
publish(cancellationRequested.get()
? stateMachine.cancel()
: stateMachine.succeed("操作完成"));
running.set(false);
onSuccess.accept(result);
});
uiDispatcher.accept(() -> completeSuccess(
generation, result, onSuccess));
} catch (Throwable error) {
if (error instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
uiDispatcher.accept(() -> {
boolean cancelled = cancellationRequested.get()
&& (error instanceof CancellationException
|| error instanceof InterruptedException);
publish(cancelled
? stateMachine.cancel()
: stateMachine.fail(readableMessage(error)));
running.set(false);
if (!cancelled) {
onFailure.accept(error);
}
});
uiDispatcher.accept(() -> completeFailure(
generation, error, onFailure));
}
});
}
public void cancel() {
if (!running.get()) return;
cancellationRequested.set(true);
publish(stateMachine.requestCancel());
synchronized (transitionLock) {
if (!running.get()
|| stateMachine.snapshot().state() != OperationState.RUNNING) {
return;
}
cancellationRequested.set(true);
publish(stateMachine.requestCancel());
}
}
public OperationSnapshot snapshot() {
@@ -90,7 +86,7 @@ public final class AsyncOperationController<T> {
return running.getReadOnlyProperty();
}
private void prepareStart(String message) {
private long prepareStart(String message) {
OperationState current = stateMachine.snapshot().state();
if (current == OperationState.SUCCEEDED || current == OperationState.FAILED
|| current == OperationState.CANCELLED) {
@@ -99,10 +95,64 @@ public final class AsyncOperationController<T> {
cancellationRequested.set(false);
publish(stateMachine.start(message));
running.set(true);
activeGeneration = ++nextGeneration;
return activeGeneration;
}
private void dispatchSnapshot(java.util.function.Supplier<OperationSnapshot> transition) {
uiDispatcher.accept(() -> publish(transition.get()));
private void dispatchProgress(long generation, String message, double progress) {
uiDispatcher.accept(() -> {
synchronized (transitionLock) {
if (generation != activeGeneration
|| stateMachine.snapshot().state() != OperationState.RUNNING) {
return;
}
publish(stateMachine.progress(message, progress));
}
});
}
private void completeSuccess(long generation, T result, Consumer<T> onSuccess) {
synchronized (transitionLock) {
if (generation != activeGeneration) {
return;
}
OperationState state = stateMachine.snapshot().state();
if (state == OperationState.RUNNING) {
publish(stateMachine.succeed("操作完成"));
} else if (state == OperationState.CANCELLING) {
publish(stateMachine.cancel());
} else {
return;
}
running.set(false);
}
onSuccess.accept(result);
}
private void completeFailure(long generation, Throwable error,
Consumer<Throwable> onFailure) {
boolean cancelled;
synchronized (transitionLock) {
if (generation != activeGeneration) {
return;
}
OperationState state = stateMachine.snapshot().state();
if (state != OperationState.RUNNING
&& state != OperationState.CANCELLING) {
return;
}
cancelled = state == OperationState.CANCELLING
&& cancellationRequested.get()
&& (error instanceof CancellationException
|| error instanceof InterruptedException);
publish(cancelled
? stateMachine.cancel()
: stateMachine.fail(readableMessage(error)));
running.set(false);
}
if (!cancelled) {
onFailure.accept(error);
}
}
private void publish(OperationSnapshot value) {
@@ -26,7 +26,7 @@ public final class OperationStateMachine {
}
public synchronized OperationSnapshot succeed(String message) {
requireState(OperationState.RUNNING, OperationState.CANCELLING);
requireState(OperationState.RUNNING);
return update(OperationState.SUCCEEDED, message, 1);
}