LWJGL Forum

Programming => Lightweight Java Gaming Library => Topic started by: TimmerCA on March 18, 2012, 23:34:00

Title: Using Java's finalize() method to dispose of VBOs
Post by: TimmerCA on March 18, 2012, 23:34:00
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?
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: Riven on March 18, 2012, 23:46:11
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.
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: Simon Felix on March 19, 2012, 01:00:16
Have a look at WeakReference and it's friends. If you need to ask how they work, do not use them  :).
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: TimmerCA on March 19, 2012, 03:03:39
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!
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: CodeBunny on March 19, 2012, 14:03:38
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.
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: RiverC on April 23, 2012, 01:30:07
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#...
Title: Re: Using Java's finalize() method to dispose of VBOs
Post by: CodeBunny on April 24, 2012, 12:27:32
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.