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

Kotlin Scripts inheriting Reference are leaking

Open CedNaru opened this issue 3 years ago • 1 comments

We tested multiples time if a Reference set as a property in a Kotlin Script is properly freed but we never tested to create a Script that inherits Reference itself.

That particular case creates a situation where the Reference will never be freed because of a cyclical reference.

Reminder: When we create an instance of a KotlinScript, we create a JVM instance of that script and set a JNI Global Ref to it in the kotlin_instance.h in CPP. This Global Ref is there so the JVM Instance won't die as long as the native object holding it is alive. That way we don't need to keep a reference to it in the Kotlin code.

Also when a JVM instance of Reference or child class is created, we automatically increase the counter of the C++ Reference. Here is our cyclical reference. To put it simply, the C++ Reference prevents the JVM Reference from dying and the JVM Reference prevents the C++ reference from dying.

CedNaru avatar Apr 23 '21 22:04 CedNaru

Note for other References issues:

  • IsInstanceValid doesn't work for references because InstanceID is wrongly used
  • A new Reference created in Koltin only to be returned by a function to C++ virtually got 0 to its counter. It's not freed just because of a delay with the JVM. But this causes a freed reference one time out of millions when bad timing with GC.

CedNaru avatar Apr 30 '21 23:04 CedNaru