scewps
scewps

Reputation: 91

LWJGL - OpenGL context gets lost in shutdown hook

I'm currently working with Java and LWJGL 3 and I'm writing some wrappers for stuff like vertex array objects, vertex buffer objects, etc. Now it's a good habit to delete these objects before program exit, so I created a shutdown hook which is supposed to do the clean up.

But when I call an OpenGL function inside of the shutdown hook I get an illegal state exception which says that an OpenGL context has not been initialized.

I've written a test program which reproduces this behaviour:

public static void main(String[] args) {
    GLFW.glfwInit();
    long window = GLFW.glfwCreateWindow(100, 100, "", 0, 0);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            GL15.glDeleteBuffers(0);
            GLFW.glfwTerminate();
        }
    });

    while (!GLFW.glfwWindowShouldClose(window)) {
        GLFW.glfwPollEvents();
    }
}

Stack Trace:

Exception in thread "Thread-0" java.lang.IllegalStateException: No GLCapabilities instance set for the current thread. Possible solutions:
a) Call GL.createCapabilities() after making a context current in the current thread.
b) Call GL.setCapabilities() if a GLCapabilities instance already exists for the current context.
at org.lwjgl.opengl.GL.getCapabilities(GL.java:241)
at org.lwjgl.opengl.GL15.nglDeleteBuffers(GL15.java:152)
at org.lwjgl.opengl.GL15.glDeleteBuffers(GL15.java:178)
at core.Main$1.run(Main.java:11)

Does anyone know why the context gets destroyed automatically?

If you need any extra information just say so.

Upvotes: 1

Views: 301

Answers (1)

BDL
BDL

Reputation: 22174

A OpenGL context is always associated with one thread (or with no thread). Functions can only be called on a particular context from the thread that the context is bound to.

Since the shutdown hook starts a new thread, you have to bind the OpenGL context to that thread before issuing any commands.

Upvotes: 1

Related Questions