Java Garbage Collection and Graphics dispose method

走远了吗. 提交于 2019-12-10 18:51:07

问题


I am creating a game (a Snake Clone) as a hobby. I was looking at the dispose method from the Graphics class in the Java API. When I comment out the dispose method, My animation works the same way just fine with or without it. In the Java API, the dispose method does this- releases system resources that the graphics context is using. Doesn't the Java garbage collection manage the memory of the program similar to what the dispose is doing? Should I keep the dispose method?

The API was not much help in explaining the sync method. But from what I read in other forums , the sync method from the ToolKit class is to ensure the drawing operation (like paintComponent method I suppose) flushes to the graphics card. So is the graphic card's job to clean up any remains of the previous graphics contexts of the program?

Here's the code:

 public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Toolkit.getDefaultToolkit().sync();
            g.dispose();

     }

回答1:


When it comes to Graphics there is a simple principle.

If you explicitly create it (e.g. BuffereImage.createGraphics()) then dispose of it.

OTOH in paintComponent(Graphics g) the instance g is provided by the toolkit and disposed of when/if it needs to be. Doing so in your own code will cause 'unpredictable' rendering.



来源:https://stackoverflow.com/questions/14096836/java-garbage-collection-and-graphics-dispose-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!