0

I write a 3d model library.

Many different models, can share same OpenGL resources, as textures, buffers, programs, vertex-attribute-objects etc.

When a model is not needed anymore, I delete it. So, if OpenGL resources go unreferenced, must be deleted too, with OpenGL API commands.

So, what of the following is better to implement?

  • Set OpenGL API command for delete OpenGL resources inside finalize() of object. I read in many articles that finalize() is a devil. I believe it, because GC can be called at any time (after OpenGL context destruction), or not at all.
  • Implement reference-counting system for java classes which handle OpenGL resources. This needs lot of code and it is like reinvent the wheel, because GC already works with reference-counting.

So, what is the best approach in cases like that?

Chameleon
  • 1,804
  • 2
  • 15
  • 21

1 Answers1

1

I guess, finalize is always wrong. The GC won't get called when you have enough heap memory... and in the meantime you may run out of the OpenGL resources. This just can't work.

GC can be called at any time (after OpenGL context destruction)

This isn't the problem (assuming that an unreferenced resource may be freed anytime; there might be threading- and order-related problems), the problem is that it may get called too late for you.

because GC already works with reference-counting.

It does not. It uses a much more efficient approach which (unlike reference-counting) can handle cycles. The cost is the non-determinism biting you, when you deal with other resources.

maaartinus
  • 44,714
  • 32
  • 161
  • 320