godot-kotlin-jvm icon indicating copy to clipboard operation
godot-kotlin-jvm copied to clipboard

New memory management using instance bindings

Open CedNaru opened this issue 1 year ago • 0 comments

This new model makes use of Godot's instance binding, a feature available for every Godot Object and reworked for 4.0 as well as the ObjectDB.

Instance Bindings allow altering the lifecycle of any Godot object, being creation, destruction, or increment/decrement of the RefCounted counter. For native Godot objects simply sent to the JVM, this binding will keep a reference to the Kotlin instance, preventing it to be collected. Before we had to keep an instance in our custom Garbage collector ourselves to keep them alive, but now that job is done directly by the binding on the C++ side. The moment the native Godot object dies, so will the JVM instance.

Regarding Refcounted Script, the solution to the cyclic references was inspired by the C# module. The concept is simple: when the counter of a Refcounter reaches 1, we know that it means the JVM is the only one still holding a reference. When it happens, the JNI reference in the binding is transformed into a weak one. The moment the JVM no longer keeps a reference to it, the RefCounted can be disposed of.

With the new ObjectDB comes a new way to handle objects, long story short, it's no longer necessary to treat RefCounted and Object differently so the code was simplified in many places.

Remains to do:

  • [ ] Make the JVM responsible for deleting the native RefCounted if it is the last one to decrement the counter.
  • [ ] There is a delay between the creation of the binding and the assignment of its JNI reference. Give the job of assigning the reference to the custom GC.

CedNaru avatar Sep 27 '22 03:09 CedNaru