开发者

When is it safe (or mandatory) to use Image.flush()?

I've been giving my first steps with images and buffered images in Java (and Java itself) and I'm a little confused about the flush() method, and M开发者_如何转开发y question is quite simple: When is it safe or even mandatory to flush an image in the code?

Doing some tests it looks like Image.flush() doesn't do anything, but BufferedImage.flush() gives some random results (sometimes some memory seems to be freed), but the component I use to paint it stops painting it on it's background.

So should I ever use Image.flush() or BufferedImage.flush() or is that something that I have to let the JVM do on it's own, or maybe do it in the finalize() method of an object?

I really can't figure it out...


You never need to call flush(), unless you want to free up memory. It basically just serves as a hint to the object to say, "Hey, go ahead and remove all your backing memory buffers now, instead of waiting for garbage collection to take care of you." It can be a useful performance optimization but it's never necessary to call.

According to the Java docs, calling flush() should leave the image in a state where it can reconstruct itself as necessary, but obviously you're running into issues where that isn't the case. Basically, don't call flush() unless you're sure you no longer need the image.

EDIT: According to a comment by @NorbertM, there are situations where an image won't be seen as deletable by the garbage collector, possibly due to image pooling or other optimizations running in the background. Basically, you should always call flush() on an image as soon as you're done with it (but no sooner).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜