126

You really can't make blanket statements about appropriate way to use all GC implementations. They vary wildly. So I'll speak to the .NET one which you originally referred to. You must know the behaviour of the GC pretty intimately to do this with any logic or reason. The only advice on collection I can give is: Never do it. If you truly know the ...


121

Does the compiler store a copy of some garbage collection program and paste it into each executable it generates? It sounds unelegant and weird, but yes. The compiler has an entire utility library, containing a whole lot more than just garbage collection code, and calls to this library will be inserted into each executable it creates. This is called the ...


102

The programmer is responsible for ensuring that objects they created via new are deleted via delete. If an object is created, but not destroyed before the last pointer or reference to it goes out of scope, it falls through the cracks and becomes a Memory Leak. Unfortunately for C, C++ and other languages which do not include a GC, this simply piles up over ...


86

Because properly knowing something is no longer referenced isn't easy. Not even close to easy. What if you have two objects referencing each other? Do they stay forever? Extending that line of thinking to resolving any arbitrary data structure, and you'll soon see why the JVM or other garbage collectors are forced to employ far more sophisticated methods of ...


82

C++ does not have garbage collection. C++ applications are required to dispose of their own garbage. C++ applications programmers are required to understand this. When they forget, the result is called a "memory leak".


79

First of all, Java has weak references and another best-effort category called soft references. Weak vs. strong references is a completely separate issue from reference counting vs. garbage collection. Second, there are patterns in memory usage that can make garbage collection more efficient in time by sacrificing space. For example, newer objects are ...


68

To understand how the two approaches compare we need to first examine how they work and the weaknesses of each. Automatic Reference counting or ARC, is a form of garbage collection in which objects are deallocated once there are no more references to them, i.e. no other variable refers to the object in particular. Each object, under ARC, contains a ...


67

Sadly, nobody there elaborates on what are such cases. I'll give some examples. All in all it is rare that forcing a GC is a good idea but it can be totally worth it. This answer is from my experience with .NET and GC literature. It should generalize well to other platforms (at least those that have a significant GC). Benchmarks of various kinds. You want ...


58

"Unspecified" and "random" are two entirely different concepts. The exact workings of a garbage collector are not specified and are up to the garbage collector (usually implemented by a VM of sorts, but not necessarily). Therefore, you have no specified (i.e. deterministic) time at which garbage will be collected. However any given implementation will ...


58

Or does the compiler include some minimal garbage collector in the compiled program's code. That’s an odd way of saying “the compiler links the program with a library that performs garbage collection”. But yes, that’s what’s happening. This is nothing special: compilers usually link tons of libraries into the programs they compile; otherwise compiled ...


57

Some advantages of reference counting over garbage collection: Low overhead. Garbage collectors can be quite intrusive (e.g. making your program freeze up at unpredictable times while a garbage collection cycle processes) and quite memory-intensive (e.g. your process's memory footprint unnecessarily grows to many megabytes before garbage-collection finally ...


55

Finalizers are important for the management of native resources. For example, your object might need to allocate a WidgetHandle from the operating system using a non-Java API. If you don't release that WidgetHandle when your object is GC'd, you're going to be leaking WidgetHandles. What's important is that the "finalizer is never called" cases break down ...


52

Garbage collection in a compiled language works the same way as in an interpreted language. Languages like Go use tracing garbage collectors even though their code is usually compiled to machine code ahead-of-time. (Tracing) garbage collection usually starts by walking the call stacks of all threads that are currently running. Objects on those stacks are ...


45

In my experience, there is one and only one reason for overriding Object.finalize(), but it is a very good reason: To place error logging code in finalize() which notifies you if you ever forget to invoke close(). Static analysis can only catch omissions in trivial usage scenarios, and the compiler warnings mentioned in another answer have such a ...


45

AFAIK, the JVM specification (written in English) does not mention when exactly an object (or a value) should be deleted, and leaves that to the implementation (likewise for R5RS). It somehow requires or suggests a garbage collector but leaves the details to the implementation. And likewise for Java specification. Remember that programming languages are ...


43

In C, C++ and other systems without a Garbage Collector, the developer is offered facilities by the language and its libraries to indicate when memory can be reclaimed. The most basic facility is automatic storage. Many times, the language itself ensures that items are disposed of: int global = 0; // automatic storage int foo(int a, int b) { static ...


41

According to Joshua Bloch's Effective Java (Second Edition), there are two scenarios when finalize() is useful: One is to act as a “safety net” in case the owner of an object forgets to call its explicit termination method. While there’s no guarantee that the finalizer will be invoked promptly, it may be better to free the resource late than never, ...


39

I've found legitimate practical applications of weak references in the following three real-world scenarios that actually happened to me personally: Application 1: Event handlers You're an entrepreneur. Your company sells a spark lines control for WPF. Sales are great but support costs are killing you. Too many customers are complaining of CPU hogging and ...


36

There are two additional items I can remember off-hand: JIT compilation Threading implementation In term of real-time, predictability of performance is probably the most important factor; That's why an unpredictable GC cycle makes Java unsuitable for real-time. JIT offers improved performances, but kicks in at some point after the program is running, ...


33

The operating system As long as Java runs on top of Unix or Windows or any other "regular" OS, realtime is not guaranteed. A real time OS is mandatory for running realtime applications.


30

No. Pretty much all modern programs use more space than is necessary. If your Java program is keeping objects alive when the programmer thinks it should be eligible for collection, it is a memory leak. It is a common, well known term. Yes, it will vary a bit by context, but the underlying concept is close enough that the mental jump is very short. ...


29

I've never done low-level programming, so I don't know how complicated can freeing resources get. Funny how the definition of "low-level" changes over time. When I was first learning to program, any language that provided a standardized heap model that makes a simple allocate/free pattern possible was considered high-level indeed. In low-level ...


28

Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. [...] Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()? Because file handles & connections (that is, file descriptors on Linux &...


27

See http://blogs.msdn.com/b/ricom/archive/2005/05/10/416151.aspx and follow all of the links to see Rico Mariani vs Raymond Chen (both very competent programmers at Microsoft) dueling it out. Raymond would improve the unmanaged one, Rico would respond by optimizing the same thing in the managed ones. With essentially zero optimization effort, the managed ...


27

C++ has this thing called RAII. Basically it means garbage gets cleaned up as you go rather than leave it in a pile and let the cleaner tidy up after you. (imagine me in my room watching the football - as I drink cans of beer and need new ones, the C++ way is to take the empty can to the bin on the way to the fridge, the C# way is to chuck it on the floor ...


26

To get good performance out of a GC, the GC needs to be able to move objects in memory. In a language like C++ where you can interact directly with memory locations, this is pretty much impossible. (Microsoft C++/CLR doesn't count because it introduces new syntax for GC-managed pointers and is thus effectively a different language.) The Boehm GC, while a ...


26

As a general principle, a garbage collector will collect when it runs into "memory pressure", and it's considered a good idea to not have it collect at other times because you could cause performance problems or even noticeable pauses in your program's execution. And in fact, the first point is dependent on the second: for a generational garbage collector, ...


26

It should be noted that it is, in the case of C++, a common misconception that "you need to do manual memory management". In fact, you don't usually do any memory management in your code. Fixed-size objects (with scope lifetime) In the vast majority of cases when you need an object, the object will have a defined lifetime in your program and is created on ...


Only top voted, non community-wiki answers of a minimum length are eligible