<p>After reading <a href="https://stackoverflow.com/questions/28832/java-and-manually-executing-finalize">this question</a>, I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity.</p>

[{'answer_id': 28960, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 0, 'selected': False, 'text': "<p>The GC does a lot of optimization on when to properly finalize things.</p>\n\n<p>So unless you're familiar with how the GC actually works and how it tags generations, manually calling finalize or start GC'ing will probably hurt performance than help.</p>\n"}, {'answer_id': 28976, 'author': 'Brian Lyttle', 'author_id': 636, 'author_profile': 'https://Stackoverflow.com/users/636', 'pm_score': 1, 'selected': False, 'text': "<p>Assuming finalizers are similar to their .NET namesake then you only really need to call these when you have resources such as file handles that can leak. Most of the time your objects don't have these references so they don't need to be called.</p>\n\n<p>It's bad to try to collect the garbage because it's not really your garbage. You have told the VM to allocate some memory when you created objects, and the garbage collector is hiding information about those objects. Internally the GC is performing optimisations on the memory allocations it makes. When you manually try to collect the garbage you have no knowledge about what the GC wants to hold onto and get rid of, you are just forcing it's hand. As a result you mess up internal calculations.</p>\n\n<p>If you knew more about what the GC was holding internally then you might be able to make more informed decisions, but then you've missed the benefits of GC.</p>\n"}, {'answer_id': 29038, 'author': 'Charles Miller', 'author_id': 3052, 'author_profile': 'https://Stackoverflow.com/users/3052', 'pm_score': 6, 'selected': True, 'text': '<p>The short answer: Java garbage collection is a very finely tuned tool. System.gc() is a sledge-hammer.</p>\n\n<p>Java\'s heap is divided into different generations, each of which is collected using a different strategy. If you attach a profiler to a healthy app, you\'ll see that it very rarely has to run the most expensive kinds of collections because most objects are caught by the faster copying collector in the young generation.</p>\n\n<p>Calling System.gc() directly, while technically not guaranteed to do anything, in practice will trigger an expensive, stop-the-world full heap collection. This is <em>almost always the wrong thing to do</em>. You think you\'re saving resources, but you\'re actually wasting them for no good reason, forcing Java to recheck all your live objects “just in case”.</p>\n\n<p>If you are having problems with GC pauses during critical moments, you\'re better off configuring the JVM to use the concurrent mark/sweep collector, which was designed specifically to minimise time spent paused, than trying to take a sledgehammer to the problem and just breaking it further.</p>\n\n<p>The Sun document you were thinking of is here: <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html" rel="noreferrer">Java SE 6 HotSpot&trade; Virtual Machine Garbage Collection Tuning</a></p>\n\n<p>(Another thing you might not know: implementing a finalize() method on your object makes garbage collection slower. Firstly, it will take <em>two</em> GC runs to collect the object: one to run finalize() and the next to ensure that the object wasn\'t resurrected during finalization. Secondly, objects with finalize() methods have to be treated as special cases by the GC because they have to be collected individually, they can\'t just be thrown away in bulk.)</p>\n'}, {'answer_id': 29138, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 2, 'selected': False, 'text': "<p>Don't bother with finalizers.  </p>\n\n<p>Switch to incremental garbage collection.</p>\n\n<p>If you want to help the garbage collector, null off references to objects you no longer need. Less path to follow= more explicitly garbage.</p>\n\n<p>Don't forget that (non-static) inner class instances keep references to their parent class instance. So an inner class thread keeps a lot more baggage than you might expect.</p>\n\n<p>In a very related vein, if you're using serialization, and you've serialized temporary objects, you're going to need to clear the serialization caches, by calling ObjectOutputStream.reset()  or your process will leak memory and eventually die.\nDownside is that non-transient objects are going to get re-serialized.\nSerializing temporary result objects can be a bit more messy than you might think!</p>\n\n<p>Consider using soft references. If you don't know what soft references are, have a read of the javadoc for java.lang.ref.SoftReference</p>\n\n<p>Steer clear of Phantom references and Weak references unless you really get excitable.</p>\n\n<p>Finally, if you really can't tolerate the GC use Realtime Java. </p>\n\n<p>No, I'm not joking.</p>\n\n<p>The reference implementation is free to download and Peter Dibbles book from SUN is really good reading.</p>\n"}, {'answer_id': 30477, 'author': 'Ron', 'author_id': 2520, 'author_profile': 'https://Stackoverflow.com/users/2520', 'pm_score': 0, 'selected': False, 'text': '<p>Avoid finalizers.  There is no guarantee that they will be called in a timely fashion.  It could take quite a long time before the Memory Management system (i.e., the garbage collector) decides to collect an object with a finalizer.  </p>\n\n<p>Many people use finalizers to do things like close socket connections or delete temporary files.  By doing so you make your application behaviour unpredictable and tied to when the JVM is going to GC your object.  This can lead to "out of memory" scenarios, not due to the Java Heap being exhausted, but rather due to the system running out of handles for a particular resource.</p>\n\n<p>One other thing to keep in mind is that introducing the calls to System.gc() or such hammers may show good results in your environment, but they won\'t necessarily translate to other systems.  Not everyone runs the same JVM, there are many, SUN, IBM J9, BEA JRockit, Harmony, OpenJDK, etc... This JVM all conform to the JCK (those that have been officially tested that is), but have a lot of freedom when it comes to making things fast.  GC is one of those areas that everyone invests in heavily.  Using a hammer will often times destroy that effort.</p>\n'}, {'answer_id': 30567, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': "<p>As far as finalizers go:</p>\n\n<ol>\n<li>They are virtually useless.  They aren't guaranteed to be called in a timely fashion, or indeed, at all (if the GC never runs, neither will any finalizers).  This means you generally shouldn't rely on them.</li>\n<li>Finalizers are not guaranteed to be idempotent.  The garbage collector takes great care to guarantee that it will never call <code>finalize()</code> more than once on the same object.  With well-written objects, it won't matter, but with poorly written objects, calling finalize multiple times can cause problems (e.g. double release of a native resource ... crash).</li>\n<li><em>Every</em> object that has a <code>finalize()</code> method should also provide a <code>close()</code> (or similar) method.  This is the function you should be calling.  e.g., <code>FileInputStream.close()</code>.  There's no reason to be calling <code>finalize()</code> when you have a more appropriate method that <em>is</em> intended to be called by you.</li>\n</ol>\n"}, {'answer_id': 5388006, 'author': 'Leo', 'author_id': 665792, 'author_profile': 'https://Stackoverflow.com/users/665792', 'pm_score': 1, 'selected': False, 'text': '<p>The real problem with closing OS handles in finalize is that the finalize are executed in no guaranteed order. But if you have handles to the things that block (think e.g. sockets) potentially your code can get into deadlock situation (not trivial at all).</p>\n\n<p>So I\'m for explicitly closing handles in a predictable orderly manner. Basically code for dealing with resources should follow the pattern:</p>\n\n<pre><code>SomeStream s = null;\n...\ntry{\n   s = openStream();\n   ....\n   s.io();\n   ...\n} finally {\n   if (s != null) {\n       s.close();\n       s = null;\n   }\n}\n</code></pre>\n\n<p>It gets even more complicated if you write your own classes that work via JNI and open handles. You need to make sure handles are closed (released) and that it will happen only once. Frequently overlooked OS handle in Desktop J2SE is <code>Graphics[2D]</code>. Even <code>BufferedImage.getGrpahics()</code> can potentially return you the handle that points into a video driver (actually holding the resource on GPU). If you won\'t release it yourself and leave it  garbage collector to do the work - you may find strange OutOfMemory and alike situation when you ran out of video card mapped bitmaps but still have plenty of memory. In my experience it happens rather frequently in tight loops working with graphics objects (extracting thumbnails, scaling, sharpening you name it).</p>\n\n<p>Basically GC does not take care of programmers responsibility of correct resource management. It only takes care of memory and nothing else. The Stream.finalize calling close() IMHO would be better implemented throwing exception new RuntimeError("garbage collecting the stream that is still open"). It will save hours and days of debugging and cleaning code after the sloppy amateurs left the ends lose.</p>\n\n<p>Happy coding.</p>\n\n<p>Peace.</p>\n'}]
['https://Stackoverflow.com/questions/28949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572/']