https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
d

Dmytro Serdiuk

11/20/2023, 11:17 PM
Hello! I have a question regarding memory management in kotlin/native and obj-c. How GC and ARC work together? Thank you
m

Marc Lefrancois

11/21/2023, 3:05 PM
Quite simple i think: The GC increments the refcount by 1 while it own’s an object and decrements it by 1 when it considers the object not part of it’s graph anymore.
d

Dmytro Serdiuk

11/21/2023, 3:11 PM
Are you sure that GC is implemented the same way as ARC in obj-c?
m

Marc Lefrancois

11/21/2023, 3:26 PM
I do not pretend to understand fully how the GC works internally. I had to work on integrating KMP with a project that does not use ARC and that’s how I notice that when I receive an object that was created by KMP, it already has a refcount of one and as soon as the GC does it thing, the refcount decreases by 1. I do not see how it could work otherwise. So from ARC perspective, the GC is simply another object taking ownership by calling
retain
and relinquishing ownership by calling
release
like we did in the old days.
d

Dmytro Serdiuk

11/21/2023, 3:28 PM
But what about code compiled from Kotlin side, that was received the obj-c object? How it will manage the ref count etc.?
m

Marc Lefrancois

11/21/2023, 3:33 PM
when an object is received by swift or objective-c ARC takes care of the refcount like any other object it creates itself
d

Dmytro Serdiuk

11/21/2023, 3:35 PM
Is there any ownership of the object in the Kotlin/native module? K/N Module received an object from iOS framework, how it’s memory would be managed? ARC works only on compile time, so there are no impact on K/N module
m

Marc Lefrancois

11/21/2023, 3:42 PM
I would guess that the Kotlin/Native module calls
retain
on a object it receives thru the GC
d

Dmytro Serdiuk

11/21/2023, 3:43 PM
@Marc Lefrancois,thank you for the feedback
m

Marc Lefrancois

11/21/2023, 4:22 PM
Maybe someone from the GC team at Jetbrains can chip in some better explanation 🙂
d

Dmytro Serdiuk

11/21/2023, 4:27 PM
I hope somebody from Kotlin team could explain. I saw this statement in the source code: “// Reference from an ObjC associated object back into a Kotlin object. // GC automatically tracks references with refcount > 0 as roots, and invalidates references with refcount = 0 when the Kotlin object is // collected. Use
create
and
dispose
to create and destroy the back reference.” Probably you are correct.
a

Alexander Shabalin [JB]

11/29/2023, 10:00 AM
Essentially, that's how it works yes. Obj-C/Swift objects are retained by the Kotlin objects until the GC decides that the Kotlin object is no longer referenced. And in the other direction Kotlin objects are being strongly held by Obj-C/Swift objects when their RC is >0.