Java Graphics Dispose Method

1.5k views Asked by At

I am wondering about a piece of code:

public void render()
{
    BufferStrategy bs = getBufferStrategy();

    if(bs == null)
    {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}

Render is in a Game Loop.

In the book I am reading, it says I need to call dispose here. I don't really understand why. Isn't it overwriting g every time render loops anyway.

2

There are 2 answers

3
Mordechai On

According to the JavaDoc is should be done for performance reasons. It will be disposed by itself through the garbage collector if all referances are released.

You're asking:

Isn't it overwriting g every time render loops anyway.

Well, in your case you create a new Graphics object every time you inquire for a graphics context. Therefore, the dispose should be called as if it is only called once, since every instance is an isolated case.

5
RealSkeptic On

Each Graphics object uses system resources, and these should be released. It's much the same as needing to call close() on an InputStream that you have opened.

If you don't do that, there is code in the finalize() method of the object that will return the resource. But it's a known issue in Java that finalize() may be called very late, or not at all, and therefore those resources will never be cleared. This can cause the program to stop working at some point when it runs out of resources.

You may be thinking that since at the end of render(), the variable g goes out of scope, it will be garbage-collected anyway. But it's merely becomes a candidate for collection. Objects that have a finalizer are not collected very quickly - the finalizer has to run before the object is completely removed. And in any case, garbage collection takes care of memory allocation, not other system resources.

This is explained in short in the documentation of the dispose() method itself.


Note that the documentation for BufferStrategy.getDrawGraphics() tells you that each time it is called, it creates a graphic context. That is, you are not getting the same object each time - it's a new object for every call of getDrawGraphics().