Skip to content

[JExtract/JNI] Add auto arena to SwiftKitCore and add memory management options #353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 7, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@

// Import javakit/swiftkit support libraries

import org.swift.swiftkit.core.SwiftArena;
import org.swift.swiftkit.core.SwiftLibraries;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;

public class HelloJava2SwiftJNI {

Expand All @@ -41,7 +41,7 @@ static void examples() {

MySwiftClass.method();

try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass myClass = MySwiftClass.init(10, 5, arena);
MySwiftClass myClass2 = MySwiftClass.init(arena);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package com.example.swift;

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

import java.util.Optional;
import java.util.OptionalInt;
Expand All @@ -26,39 +26,39 @@
public class MySwiftClassTest {
@Test
void init_noParameters() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
assertNotNull(c);
}
}

@Test
void init_withParameters() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(1337, 42, arena);
assertNotNull(c);
}
}

@Test
void sum() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(30, c.sum());
}
}

@Test
void xMultiplied() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(200, c.xMultiplied(10));
}
}

@Test
void throwingFunction() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
Exception exception = assertThrows(Exception.class, () -> c.throwingFunction());

Expand All @@ -68,15 +68,15 @@ void throwingFunction() {

@Test
void constant() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(100, c.getConstant());
}
}

@Test
void mutable() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(0, c.getMutable());
c.setMutable(42);
Expand All @@ -86,15 +86,15 @@ void mutable() {

@Test
void product() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(200, c.getProduct());
}
}

@Test
void throwingVariable() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);

Exception exception = assertThrows(Exception.class, () -> c.getThrowingVariable());
Expand All @@ -105,7 +105,7 @@ void throwingVariable() {

@Test
void mutableDividedByTwo() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertEquals(0, c.getMutableDividedByTwo());
c.setMutable(20);
Expand All @@ -117,15 +117,15 @@ void mutableDividedByTwo() {

@Test
void isWarm() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(20, 10, arena);
assertFalse(c.isWarm());
}
}

@Test
void sumWithX() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
MySwiftClass c2 = MySwiftClass.init(50, 10, arena);
assertEquals(70, c1.sumX(c2));
Expand All @@ -134,7 +134,7 @@ void sumWithX() {

@Test
void copy() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
MySwiftClass c2 = c1.copy(arena);

Expand All @@ -146,7 +146,7 @@ void copy() {

@Test
void addXWithJavaLong() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c1 = MySwiftClass.init(20, 10, arena);
Long javaLong = 50L;
assertEquals(70, c1.addXWithJavaLong(javaLong));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

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

public class MySwiftStructTest {
@Test
void init() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
assertEquals(1337, s.getCapacity());
assertEquals(42, s.getLen());
Expand All @@ -31,7 +32,7 @@ void init() {

@Test
void getAndSetLen() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
s.setLen(100);
assertEquals(100, s.getLen());
Expand All @@ -40,7 +41,7 @@ void getAndSetLen() {

@Test
void increaseCap() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftStruct s = MySwiftStruct.init(1337, 42, arena);
long newCap = s.increaseCap(10);
assertEquals(1347, newCap);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package com.example.swift;

import org.junit.jupiter.api.Test;
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
import org.swift.swiftkit.core.SwiftArena;

import java.util.Optional;
import java.util.OptionalDouble;
Expand Down Expand Up @@ -82,7 +82,7 @@ void optionalString() {

@Test
void optionalClass() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
assertEquals(Optional.empty(), MySwiftLibrary.optionalClass(Optional.empty(), arena));
Optional<MySwiftClass> optionalClass = MySwiftLibrary.optionalClass(Optional.of(c), arena);
Expand All @@ -99,7 +99,7 @@ void optionalJavaKitLong() {

@Test
void multipleOptionals() {
try (var arena = new ConfinedSwiftMemorySession()) {
try (var arena = SwiftArena.ofConfined()) {
MySwiftClass c = MySwiftClass.init(arena);
OptionalLong result = MySwiftLibrary.multipleOptionals(
Optional.of((byte) 1),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,29 +247,47 @@ extension JNISwift2JavaGenerator {
guard let translatedDecl = translatedDecl(for: decl) else {
fatalError("Decl was not translated, \(decl)")
}
let translatedSignature = translatedDecl.translatedFunctionSignature

var modifiers = ["public"]

if decl.isStatic || decl.isInitializer || !decl.hasParent {
modifiers.append("static")
}

let translatedSignature = translatedDecl.translatedFunctionSignature
let resultType = translatedSignature.resultType.javaType
var parameters = translatedDecl.translatedFunctionSignature.parameters.map({ $0.parameter.renderParameter() })
if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena$")
}
var parameters = translatedDecl.translatedFunctionSignature.parameters.map { $0.parameter.renderParameter() }
let throwsClause = decl.isThrowing ? " throws Exception" : ""

var annotationsStr = translatedSignature.annotations.map({ $0.render() }).joined(separator: "\n")
if !annotationsStr.isEmpty { annotationsStr += "\n" }

let modifiersStr = modifiers.joined(separator: " ")
let parametersStr = parameters.joined(separator: ", ")

// Print default global arena variation
if config.effectiveMemoryManagementMode.requiresGlobalArena && translatedSignature.requiresSwiftArena {
printDeclDocumentation(&printer, decl)
printer.printBraceBlock(
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parametersStr))\(throwsClause)"
) { printer in
let globalArenaName = "SwiftMemoryManagement.GLOBAL_SWIFT_JAVA_ARENA"
let arguments = translatedDecl.translatedFunctionSignature.parameters.map(\.parameter.name) + [globalArenaName]
let call = "\(translatedDecl.name)(\(arguments.joined(separator: ", ")))"
if translatedDecl.translatedFunctionSignature.resultType.javaType.isVoid {
printer.print("\(call);")
} else {
printer.print("return \(call);")
}
}
printer.println()
}

if translatedSignature.requiresSwiftArena {
parameters.append("SwiftArena swiftArena$")
}
printDeclDocumentation(&printer, decl)
printer.printBraceBlock(
"\(annotationsStr)\(modifiersStr) \(resultType) \(translatedDecl.name)(\(parametersStr))\(throwsClause)"
"\(annotationsStr)\(modifiers.joined(separator: " ")) \(resultType) \(translatedDecl.name)(\(parameters.joined(separator: ", ")))\(throwsClause)"
) { printer in
printDowncall(&printer, decl)
}
Expand Down
5 changes: 5 additions & 0 deletions Sources/JavaKitConfigurationShared/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public struct Configuration: Codable {
minimumInputAccessLevelMode ?? .default
}

public var memoryManagementMode: JExtractMemoryManagementMode?
public var effectiveMemoryManagementMode: JExtractMemoryManagementMode {
memoryManagementMode ?? .default
}

// ==== java 2 swift ---------------------------------------------------------

/// The Java class path that should be passed along to the swift-java tool.
Expand Down
22 changes: 22 additions & 0 deletions Sources/JavaKitConfigurationShared/GenerationMode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,25 @@ extension JExtractMinimumAccessLevelMode {
.public
}
}


/// Configures how memory should be managed by the user
public enum JExtractMemoryManagementMode: String, Codable {
/// Force users to provide an explicit `SwiftArena` to all calls that require them.
case explicit

/// Provide both explicit `SwiftArena` support
/// and a default global automatic `SwiftArena` that will deallocate memory when the GC decides to.
case allowGlobalAutomatic

public static var `default`: Self {
.explicit
}

public var requiresGlobalArena: Bool {
switch self {
case .explicit: false
case .allowGlobalAutomatic: true
}
}
}
9 changes: 9 additions & 0 deletions Sources/SwiftJavaTool/Commands/JExtractCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ extension SwiftJava {
@Option(help: "The lowest access level of Swift declarations that should be extracted, defaults to 'public'.")
var minimumInputAccessLevel: JExtractMinimumAccessLevelMode = .default

@Option(help: "The memory management mode to use for the generated code. By default, the user must explicitly provide `SwiftArena` to all calls that require it. By choosing `allow-automatic`, user can omit this parameter and a global GC-based arena will be used. `force-automatic` removes all explicit memory management.")
var memoryManagementMode: JExtractMemoryManagementMode = .default

@Option(
help: """
A swift-java configuration file for a given Swift module name on which this module depends,
Expand All @@ -89,6 +92,7 @@ extension SwiftJava.JExtractCommand {
config.writeEmptyFiles = writeEmptyFiles
config.unsignedNumbersMode = unsignedNumbers
config.minimumInputAccessLevelMode = minimumInputAccessLevel
config.memoryManagementMode = memoryManagementMode

try checkModeCompatibility()

Expand Down Expand Up @@ -117,6 +121,10 @@ extension SwiftJava.JExtractCommand {
case .wrapGuava:
() // OK
}
} else if self.mode == .ffm {
guard self.memoryManagementMode == .explicit else {
throw IllegalModeCombinationError("FFM mode does not support '\(self.memoryManagementMode)' memory management mode! \(Self.helpMessage)")
}
}
}
}
Expand Down Expand Up @@ -148,3 +156,4 @@ struct IllegalModeCombinationError: Error {
extension JExtractGenerationMode: ExpressibleByArgument {}
extension JExtractUnsignedIntegerMode: ExpressibleByArgument {}
extension JExtractMinimumAccessLevelMode: ExpressibleByArgument {}
extension JExtractMemoryManagementMode: ExpressibleByArgument {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 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 org.swift.swiftkit.core;


import org.swift.swiftkit.core.ref.SwiftCleaner;

import java.util.Objects;
import java.util.concurrent.ThreadFactory;

/**
* A memory session which manages registered objects via the Garbage Collector.
*
* <p> When registered Java wrapper classes around native Swift instances {@link SwiftInstance},
* are eligible for collection, this will trigger the cleanup of the native resources as well.
*
* <p> This memory session is LESS reliable than using a {@link ConfinedSwiftMemorySession} because
* the timing of when the native resources are cleaned up is somewhat undefined, and rely on the
* system GC. Meaning, that if an object nas been promoted to an old generation, there may be a
* long time between the resource no longer being referenced "in Java" and its native memory being released,
* and also the deinit of the Swift type being run.
*
* <p> This can be problematic for Swift applications which rely on quick release of resources, and may expect
* the deinits to run in expected and "quick" succession.
*
* <p> Whenever possible, prefer using an explicitly managed {@link SwiftArena}, such as {@link SwiftArena#ofConfined()}.
*/
final class AutoSwiftMemorySession implements SwiftArena {
private final SwiftCleaner swiftCleaner;

public AutoSwiftMemorySession(ThreadFactory cleanerThreadFactory) {
this.swiftCleaner = SwiftCleaner.create(cleanerThreadFactory);
}

@Override
public void register(SwiftInstance instance) {
Objects.requireNonNull(instance, "value");

// We make sure we don't capture `instance` in the
// cleanup action, so we can ignore the warning below.
var cleanupAction = instance.$createCleanup();
swiftCleaner.register(instance, cleanupAction);
}
}
Loading
Loading