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 My 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).
Related
After
Runtime.getRuntime().exec(command);
i see syscalls happening that show 2~3 file descriptors (FIFO pipes). What is the proper way to close them with try-with-resource pattern?
Most historical tribal knowledge found on java forums suggest:
# out of date!
... } finally {
IOUtils.closeQuietly(p.getOutputStream());
IOUtils.closeQuietly(p.getInputStream());
IOUtils.closeQuietly(p.getErrorStream());
}
but that doesn't sound right because 1) method closeQuietly is deprecated and most libraries suggest using try-with-resource, 2) it is inelegant as I might not necessarily have all streams.
And simply moving the exec() call into try feels wrong as it is not the resource i will call close() on.
Closing them isn't necessary; the close by themselves when the process dies. If the process never dies, it is also not neccessary: Either you make a new never-dying process every so often in which case your system is going to crash and run out of resources whether you close these or not, or you make it only once, in which case these resources aren't going to count for much. For what it is worth, these are quite lightweight resources, and often they simply cannot be 'closed' in the sense that the resources can be 'freed' - closing them either keeps them open but denies further chat (and sends EOFs where needed), or reroutes them to /dev/null; generally processes just have 3 pipes on em and will continue to have them until the process dies.
Yes, closeQuietly is a silly idea for virtually all purposes, and so it is here. If closing these streams somehow fail you probably don't want to silently ignore that.
If you must close them, the individual streams from these 3 are closable. However, note that you're reading rules of thumb and attempting to apply them as if they are gospel truth. try-with-resources is not always the right answer, and try-with-resources is not a 100% always replacement for close, let alone closeQuietly.
For example, try-with-resources specifically is designed around a period of usage. You declare the span of statements within which the resource should be available (the braces that go with the try block), and the construct will then ensure that the resource is closed only once code flow transitions out of that span of statements, no matter how it exits this. That makes it probably irrelevant here, too!
You are starting a long-lived process and don't care about the in/out. You just want the process to run and to keep running. This means there is no span at all, and you should just call close() on these if somehow you feel it is important to try to save the resources even though most likely this accomplishes nothing at all. No span-of-statements means try-with-resources isn't right.
You are starting a short-lived process that you interact with. The right thing to 'close' is the process itself, except you can't use try-with-resources for that. That can only be used on auto-closables. (resources where the class that represents them implement AutoClosable. Most do, some don't. Lock is a famous one. Process is another: To 'close' it, you invoke destroy() or even destroyForcibly(). You cannot use try-with-resources (not without ugly hacks that defeats the purpose) to do this! Once you close/destroy the process, the streams that went along with them are dead too.
More generally the principle is: If you create it, you close it. If you never call getOutputStream() you never created them. On some OSes, fetching these streams and then closing them wastes more resources than not doing this. Thus, if the argument is based on some sort of purity model, then you shouldn't close them either. If it's based on pragmatics, you'd have to test how heavy these resources really are (most likely, extremely light), whether closing them actually saves you some pipes (most likely, it will not), and whether close()-ing the result of invoking getOutputStream() on the process even helps if the answers to the above questions make that relevant (it probably will, but the spec does not guarantee this).
They are very light processes that in almost every case don't require closing...
I have created an object whose finalize method has been overridden to save and close the file with some information. That object is weak referenced from another object. I want to save some changes to the object when GC happens. That's why I have overridden the code for finalize.
But, the finalize method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.
I dont want this, I want to call the finalize method as soon as GC happens, and there should not be any lag. Is there any jvm option which I can set to achieve this ??
There is only one other way which I can see is "System.runFinalization()", but that seems tacky??
Is there a more elegant way?
Thanks
I want to call the finalize method as soon as GC happens,
You can't without using internal APIs I wouldn't recommend you use.
there should not be any lag.
There is always lag. Just closing the file will take many milli-seconds. Are you okay with the application freezing while this happens (because the application can freeze while the GC is running)
Is there a more elegant way?
Close the resource when you finish with it if you want to to happen deterministically.
this question is for either android or java .
suppose i have an instance of a class (even a thread) .
i wish that in order to make it fool proof against forgetting to dispose/close the instance (and avoid any possible memory leaks) , if there are no more references to this instance , it will automatically call a specific method , disposing/closing itself (in case of a thread , it will probably interrupt itself) .
is it possible to enforce such a thing?
if needed , i don't mind that such a thing will occur only during GC .
if there are no more references to this instance , it will
automatically call a specific method , disposing/closing itself (in
case of a thread , it will probably interrupt itself)
finalize() does what you describe here. You very rarely see it used though, and there are some pitfalls when using it. As you cant control garbage collection, you cant be sure when finalize will be run, if ever! From the api:
the usual purpose of finalize, however, is to perform cleanup actions
before the object is irrevocably discarded. For example, the finalize
method for an object that represents an input/output connection might
perform explicit I/O transactions to break the connection before the
object is permanently discarded.
You cant enforce garbage collection. You can only suggest the JVM to do so using System.gc(), but it is not guaranteed that it will be done.
I know this is very late but I hope it might help someone someday.
You can receive such events this by using the using the library that i am developing called gcRadar. It provides events when an object is orphaned and after the actual garbage collection of the object.
Any suggestions for improvements in the library are welcome.
There is no way to access the references held by the VM. As Zavior suggested, the only way to know for sure that an object, or an "island" of objects is inaccessible, is to use the finalize method.
Please note that you will only get notified during GC runs. So it does not really help closing/disposing resources that are still referenced but should be closed. If you want to do that as well and do not want to use such constructs as try/catch/finally, you should write a manager class for the resources.
With any of the possibillities, including a manager class, you will not get a "bulletproof" way to consolidate your resources. Being careful is the best solution IMHO.
EDIT:
I have found this thread that may be useful.
It seems more efficient to store events on the dispatcher if they're never going to change. Isn't creating them costly? Is there some kind of information I'm losing if I dispatch an already-stored event?
Essentially what your asking is a specific use case of object pooling, and the performance of object pooling vs. object creation. Languages like Java don't get much benefit from object pooling because Java does this for you. And does it better than if you were to do it on your own. In fact Java engineers have made it very clear you shouldn't do this because Java allocates, scales, and handles thousands of objects better than you can. That's the whole point of GC. Object allocation in Java is already doing pooling for you, but at a lower level that's why memory allocation in Java and other languages is way faster than C. Every object allocated in Java comes from a ready made memory pool by the JVM.
http://www.ibm.com/developerworks/java/library/j-jtp09275.html?ca=dgr-jw22JavaUrbanLegends
Another reason events are created at dispatch time, instead of caching them, is they carry parameters in them that change between each dispatch. For example, what character was typed, where the mouse was clicked, etc. Recycling events might sound like a good idea until you do it, and all of a sudden you're sending old information with the wrong event. Better to just new that event up each time and have it properly initialize itself with the right data. It's simpler for the author and less error prone.
There are also technical problems you might encounter if you reused events. Event cancellation schemes usually store that information in the event that is modified after dispatch by some listener. In actionscript you can say event.preventDefault() to affect the chaining of event listeners. What happens if you start reusing that event after preventDefault has been called? And at what time is it safe to say this event isn't being used by a listener that has yet to fire (callLater/invokeLater makes it hard). There's no callback in either Java/Actionscript that says this event is ok to reuse (no reclamation semantics to return the object to the pool).
That's not to say you could find a case where holding onto the event and reusing it performs better. But, just because it's faster for those high performance cases doesn't mean it's a good idea for everything every time. Remember don't optimize until you know there's a problem.
I had the general view that clean up of resources is done in the finally block,
recently I found this particular code snippet in a class and it was overriding the Object class' finalize() method.
protected void finalize() {
try {
In.close();
Out.close();
socket.close();
}
catch (Exception e) {
//logger code here
}
}
Is this a good idea? What are the pros and cons of finalize() over finally?
The finally block is just a block of code that always executes after a try block, even if there is an exception. i.e. it is local in scope
The finalize() method is an approach for cleaning up the whole object when it is garbage collected.
Java documentation of finalize()
finally solves the problem of cleaning up resources in a block of code regardless of whether an exceptional condition occurs...
finalize() is a way to clean up resources when your object is no longer being used, once the Garbage Collecter determines there are no more references to that object.
In short, to answer your question, for example, if the sockets you are closing are members of an object you should close them in the finalize() method, (although that's sub-optimal, and just for example, because there is no guarantee when the GC will actually perform the action)
If however you're opening the socket in a method, and are done with it when the method ends you should free the resources in the finally block.
Always clean up things in finally.
Cleaning up in finalize is not guaranteed to occur.
However, it is often found to clean up such things in finalizers as a last-ditch safety valve should a finally block throw another exception on you.
The real problem with relying on finalizers is something else may need the resource before the GC gets around to calling the finalizer.
Phantom References will do what you want.
Just don't use finalize. There are a few edge cases where it may be helpful (printing debug info when a class is GC'd has come in handy), but in general don't. There is nothing in the JVM contract that even says it ever has to be called.
There is a very under-publicized type of object called "References". One is made explicitly for things that you think you would use finalize for.
"Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed."
It just occurred to me that there MUST be a description of this on the web--so I'll replace all the "how-to" stuff I just wrote with this reference.
They're not related. This is like asking, "Should you create objects in an initializer or in normal methods?" Like, it depends on what you're doing with the objects. A finalizer cleans up an object's state while it's destroyed (maybe — it's not something you should rely on), while a finally block executes code after a try block. There isn't any common situation where you'd be able to choose one or the other since they do different things.
Finalize is probably a bad idea if your application causes lots of these objects to be created. This is because finalize will cause a bottleneck as the objects become eligible for garbage collection.
There are times when finalize is the only solution; but use finally whenever you can
Finally. Finalize is bad in that it may never get called. Use finalize only as a safety net. For example an InputStream should have a finalize that closes the stream incase the applcicationforgets to. However the application should close it.
If it were me I would do the cleanup in the finalizer as well and log the cases when the cleanup was performed and then track down in the application the code that forgot to properly clean up.
There are a number of problems with the code in the question, including:
The big problem: It looks like you are trying to close a socket. Even if you don't close it properly, it will close in its own finaliser. Adding another finaliser doesn't make it any more closed.
An exception thrown by the first close will prevent the others from executing (as it happens, this doesn't matter in this example because of the peculiar behaviour of Socket).
If you do override finalize, leave it throwing Throwable (and add #Override). Technically you should also call the super in a finally block.
The Java Memory Model is mighty strange when it comes to finalisers (previous execution of code does not necessarily happen-before the execution of the finaliser). I would explain the problem, but what you need to know is that you need to stay away from finalisers.
So: Always use finally for these things. finalize is extremely specialised (and PhantomReference are probably better is superficially more complicated).
If you are looking for alternatives to finalize() the proper question would be:
Why use an explicit close() method like, for example, all the stream and writer/reader classes in java.io.* and many others - when there is finalize()?
The other answers make it clear that the disadvantage of finalize() is that you have no way to force it to run, and neither do any who might use your code.
Of course, calling a close() methode (best done in a finally block or in a close() method itself) has to be documented by the author and then remembered to be called by the ones using the code. But there are lots of examples (not only java.io.*) where this is imposed and it works.
BTW: close() is merely a convention.
Joshua Bloch makes a very clear recommendation in his book Effective Java (2nd Edition). Copied from chapter 2 Item 7: Avoid finalizers:
Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, which we’ll cover later in this item, but as a rule of thumb, you should avoid finalizers.
Please read the reference to find out why.