Search code examples
javacallbackuser-inputlwjglglfw

Java glfwSetScrollCallback, do to 'cbfun' for Memory Leaks?


I was just curious ... when using glfwSetScrollCallback(window, scrollfun) in java, GLFW 3.2, do I need to release/remove the callback at anytime, as in, glfwSetScrollCallback(window, null)? Will it cause memory leaks or increased usage if I do not?

I just want to make sure that I am using it without causing too much additional strain. I do understand that I can use this to disable getting the callback at certain times, which is nice, and kind of handy to multi game builds, etc.


Solution

  • There is nothing on the GLFW side that may cause any memory leaks for non-released window callbacks, such as the scroll callback, because GLFW itself does not own that memory. It is just a function pointer kept in a per-window variable (that exists anyways - otherwise it is NULL).

    From the LWJGL side, which owns the memory for the callback object, instantiating the callback class to an object implementing the callback Java interface does require both JVM on-heap as well as off-heap memory.

    When you instantiate the callback object (e.g. org.lwjgl.glfw.GLFWScrollCallback), then you must also call its free() methode (inherited from org.lwjgl.system.NativeResource) in order to dispose of the allocated native memory (LWJGL 3 does not use the finalize() mechanism). Currently, LWJGL 3 uses the dyncall library to generate native executable code for generated callback functions.

    So: You can register and unregister a single instantiated callback object on a GLFW window as many times as you like, without any issues. Just make sure that you do it in a thread-safe manner by only calling window-related functions on the main thread. See the GLFW functions' documentation for that.