Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import Synchronization

public final class AsyncCancellationProbe: Sendable {
private struct State {
var cancelled = false
var waitingToReturn: CheckedContinuation<Void, Never>?
var destroyedResults: Int32 = 0
}

private let state = Mutex(State())

public init() {}

public func waitForCancellation() async throws -> Int64 {
do {
try await Task.sleep(for: .seconds(60))
return 1
} catch {
state.withLock { $0.cancelled = Task.isCancelled }
throw error
}
}

public func waitForOptionalCancellation() async throws -> Int64? {
try await waitForCancellation()
}

public func makeOwnedResult() async -> AsyncOwnedResult {
newOwnedResult()
}

public func makeOwnedResults() async -> [AsyncOwnedResult] {
[newOwnedResult(), newOwnedResult()]
}

public func makeOwnedTuple() async -> (AsyncOwnedResult, [String: AsyncOwnedResult], Set<Int32>) {
(newOwnedResult(), ["value": newOwnedResult()], [42])
}

private func newOwnedResult() -> AsyncOwnedResult {
AsyncOwnedResult { [self] in state.withLock { $0.destroyedResults += 1 } }
}

public func returnOwnedResultWhenAllowed() async -> AsyncOwnedResult {
await withCheckedContinuation { continuation in
state.withLock { $0.waitingToReturn = continuation }
}
return newOwnedResult()
}

public func returnOwnedResultAfterCancellation() async -> AsyncOwnedResult {
_ = try? await waitForCancellation()
return newOwnedResult()
}

public func returnOwnedResultsAfterCancellation() async -> [AsyncOwnedResult] {
_ = try? await waitForCancellation()
return [newOwnedResult(), newOwnedResult()]
}

public func wasCancelled() -> Bool { state.withLock { $0.cancelled } }

public func isWaitingToReturn() -> Bool { state.withLock { $0.waitingToReturn != nil } }

public func allowReturn() {
let continuation = state.withLock {
let continuation = $0.waitingToReturn
$0.waitingToReturn = nil
return continuation
}
continuation?.resume()
}

public func destroyedResults() -> Int32 { state.withLock { $0.destroyedResults } }
}

public final class AsyncOwnedResult: Sendable {
private let onDestroy: @Sendable () -> Void

fileprivate init(onDestroy: @escaping @Sendable () -> Void) {
self.onDestroy = onDestroy
}

deinit {
onDestroy()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

package com.example.swift;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.swift.swiftkit.core.SwiftArena;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;

import static org.junit.jupiter.api.Assertions.*;

public class AsyncCancellationTest {
@ParameterizedTest
@ValueSource(strings = {"scalar", "optional"})
void cancelsSwiftTask(String resultType) throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
Future<?> future = switch (resultType) {
case "scalar" -> probe.waitForCancellation();
case "optional" -> probe.waitForOptionalCancellation();
default -> throw new IllegalArgumentException();
};
assertTrue(future.cancel(false));
awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation");
}
}

@ParameterizedTest
@ValueSource(strings = {"orTimeout", "completeOnTimeout", "complete", "completeExceptionally"})
void completionCancelsSwiftTask(String completion) throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
var future = probe.waitForCancellation();
switch (completion) {
case "orTimeout" -> {
future.orTimeout(10, TimeUnit.MILLISECONDS);
var failure = assertThrows(ExecutionException.class, () -> get(future));
assertInstanceOf(TimeoutException.class, failure.getCause());
}
case "completeOnTimeout" -> {
future.completeOnTimeout(42L, 10, TimeUnit.MILLISECONDS);
assertEquals(42L, get(future));
}
case "complete" -> {
assertTrue(future.complete(42L));
assertEquals(42L, get(future));
}
case "completeExceptionally" -> {
var error = new IllegalStateException("Completed by caller");
assertTrue(future.completeExceptionally(error));
var failure = assertThrows(ExecutionException.class, () -> get(future));
assertSame(error, failure.getCause());
}
default -> throw new IllegalArgumentException();
}
awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation");
}
}

@Test
void closingArenaReleasesResult() throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
try (var resultArena = SwiftArena.ofConfined()) {
var result = get(probe.makeOwnedResult(resultArena));
assertFalse(result.$cleanup().isDestroyed());
assertEquals(0, probe.destroyedResults());
}
awaitCondition(() -> probe.destroyedResults() == 1, "Swift result was not destroyed");
}
}

@Test
void closingArenaReleasesTupleResults() throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
try (var resultArena = SwiftArena.ofConfined()) {
assertNotNull(get(probe.makeOwnedTuple(resultArena)));
assertEquals(0, probe.destroyedResults());
}
awaitCondition(() -> probe.destroyedResults() == 2, "Swift tuple elements were not destroyed");
}
}

@ParameterizedTest
@ValueSource(ints = {1, 2})
void cancelBeforeArenaTakesOwnership(int expectedDestroyed) throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
try (var resultArena = SwiftArena.ofConfined()) {
Future<?> future = switch (expectedDestroyed) {
case 1 -> probe.returnOwnedResultAfterCancellation(resultArena);
case 2 -> probe.returnOwnedResultsAfterCancellation(resultArena);
default -> throw new IllegalArgumentException();
};
assertTrue(future.cancel(false));
awaitCondition(probe::wasCancelled, "Swift task did not observe cancellation");
}
awaitCondition(() -> probe.destroyedResults() == expectedDestroyed, "Late Swift results were not destroyed");
}
}

@Test
void cancelAfterArenaTakesOwnership() throws Exception {
try (var probeArena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(probeArena);
try (var resultArena = SwiftArena.ofConfined()) {
var futureToCancel = new AtomicReference<Future<?>>();
Future<AsyncOwnedResult> future = probe.returnOwnedResultWhenAllowed(instance -> {
resultArena.register(instance);
futureToCancel.get().cancel(false);
});
futureToCancel.set(future);

awaitCondition(probe::isWaitingToReturn, "Swift task did not pause before returning");
probe.allowReturn();

assertThrows(CancellationException.class, () -> get(future));
assertEquals(0, probe.destroyedResults());
}
awaitCondition(() -> probe.destroyedResults() == 1, "Swift result was not destroyed");
}
}

@Test
void releaseElementsIfArenaIsAlreadyClosed() throws Exception {
try (var arena = SwiftArena.ofConfined()) {
var probe = AsyncCancellationProbe.init(arena);
var closedArena = SwiftArena.ofConfined();
closedArena.close();

var failure = assertThrows(ExecutionException.class, () -> get(probe.makeOwnedResults(closedArena)));
assertEquals("SwiftArena is already closed!", failure.getCause().getMessage());
awaitCondition(() -> probe.destroyedResults() == 2, "Swift array elements were not destroyed");
}
}

private static <T> T get(Future<T> future) throws InterruptedException, ExecutionException, TimeoutException {
return future.get(5, TimeUnit.SECONDS);
}

private static void awaitCondition(BooleanSupplier condition, String message) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (!condition.getAsBoolean()) {
assertTrue(System.nanoTime() - deadline < 0, message);
Thread.sleep(5);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,7 @@ extension JNISwift2JavaGenerator {
}

if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena")
parameters.append("SwiftArena \(ArenaParameterName.caller)")
}
if let importedFunc {
TranslatedDocumentation.printDocumentation(
Expand Down Expand Up @@ -1016,8 +1016,9 @@ extension JNISwift2JavaGenerator {

// Indirect return receivers
for outParameter in translatedFunctionSignature.result.outParameters {
let initializer = outParameter.allocation.render(type: outParameter.type, printer: &printer)
printer.print(
"\(outParameter.type) \(outParameter.name) = \(outParameter.allocation.render(type: outParameter.type));"
"\(outParameter.type) \(outParameter.name) = \(initializer);"
)
arguments.append(outParameter.name)
}
Expand Down
Loading
Loading