Using Java's finalize() method to dispose of VBOs

Started by TimmerCA, March 18, 2012, 23:34:00

Previous topic - Next topic

TimmerCA

I'm implementing game objects in a class like this:

public abstract class GameObject {
  private int vbo_id = 0;

  public GameObject() {
    vbo_id = GL15.glGenBuffers();
  }

  @Override
  public void finalize() throws Throwable {
    super.finalize();
    
    GL15.glDeleteBuffers(vbo_id);  
  }

  // snip lots of other game object methods
}


Each type of game object will be implemented with this class as its base.  Obviously there will be a method to generate the VBO and load it into OpenGL, and other methods to react to certain game conditions.

I've been reading up on Java's finalize() method and I see a lot of people saying not to use it, but I can't see any other way to guarantee that the VBO gets released in OpenGL when the object is discarded.  Is there a better way to do this?

Riven

Regardless of correctness, you have the additional problem of the GC thread calling that method. The OpenGL context will not be current on that thread.

You really have to do your own bookkeeping to solve this problem. It's not hard either.

Simon Felix

Have a look at WeakReference and it's friends. If you need to ask how they work, do not use them  :).
Download Cultris II, the fastest Tetris clone from http://gewaltig.net/

TimmerCA

Quote from: Riven on March 18, 2012, 23:46:11
You really have to do your own bookkeeping to solve this problem. It's not hard either.

Blarg.  Oh well.  So it is.  Thanks!

CodeBunny

The problem is also that finalize is not required to be called; it relies on the active GC strategy. Usually, garbage collection doesn't often occur unless the JVM is close to maximum memory (which rarely happens).

I had the same idea once, and was quite let down when it turned out to not be possible.

RiverC

Anyway, when objects need to removed, you'll know because you're removing them, right? I mean, if they go out of range (in a different level or too far away) or are destroyed, you'll be doing it yourself. So release the VBO then (I would assume) because they will stop being rendered, anyway.

Java GC can be a little wack anyway. At least it's not as bananas as C#...

CodeBunny

Well, yes, it's not too hard to keep track of everything, but it still would be nice to just treat OpenGL objects the same way as Java objects.