garbage-collection interview questions
Top garbage-collection frequently asked interview questions
Consider the following C# program, I submitted it on codegolf as an answer to create a loop without looping:
class P{
static int x=0;
~P(){
System.Console.WriteLine(++x);
new P();
}
static void Main(){
new P();
}
}
This program looks like an infinite loop in my inspection, but it seems to run for several thousand iterations, and then the program terminates successfully without error (No errors are thrown). Is it a spec violation that the finalizer for P
eventually is not called?
Clearly this is stupid code, that should never appear, but I am curious as to how the program could ever complete.
Original code golf post::
http://codegolf.stackexchange.com/questions/33196/loop-without-looping/33218#33218
Source: (StackOverflow)
I've searched, but I've not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what's its real advantage? What are the problems of static and stack? Could I write an entire application without allocating variables in the heap?
I heard that others languages incorporate a "garbage collector" so you don't have to worry about memory. What does the garbage collector do?
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Once someone said to me that with this declaration:
int * asafe=new int;
I have a "pointer to a pointer". What does it mean? It is different of:
asafe=new int;
?
Source: (StackOverflow)
I'm looking for a document that describes in details how python garbage collection works? I'm interested what is done in which step. What objects are in these 3 collections? What kinds of objects are deleted in each step? What algorithm is used for reference cycles finding?
Background of this is I'm implementing some searches that have to finish in small amount of time. When garbage collector collect oldest generation, it is much
slower than in other cases. It took more time than it is intended for searches. I'm looking how to predict when it will collect oldest generation and how long it will take.
It is easy to predict when it will collect oldest generation with get_count()
and get_threshold()
. That also can be manipulated with set_threshold()
. But I don't see how easy to decide is it better to make collect()
by force or wait for scheduled collection.
Source: (StackOverflow)
I have a class that offers up a few events. That class is declared globally but not instanced upon that global declaration--it's instanced on an as-needed basis in the methods that need it.
Each time that class is needed in a method, it is instanced and event handlers are registered. Is it necessary to remove the event handlers explicitly before the method goes out of scope?
When the method goes out of scope, so goes the instance of the class. Does leaving event handlers registered with that instance that is going out of scope have a memory footprint implication? (I'm wondering if the event handler keeps the GC from seeing the class instance as no longer being referenced.)
Thank you.
Source: (StackOverflow)
Consider the below code:
public class Class1
{
public static int c;
~Class1()
{
c++;
}
}
public class Class2
{
public static void Main()
{
{
var c1=new Class1();
//c1=null; // If this line is not commented out, at the Console.WriteLine call, it prints 1.
}
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(Class1.c); // prints 0
Console.Read();
}
}
Now, even though the variable c1 in the main method is out of scope and not referenced further by any other object when GC.Collect()
is called, why is it not finalized there?
Source: (StackOverflow)
From my understanding, garbage collection in java cleans up some object iff nothing else is 'pointing' to that object. My question is, what happens if we have something like:
class Node{
public object value;
public Node next;
public Node(object o, Node n) { value = 0; next = n;}
}
//...some code
{
Node a = new Node("a", null),
b = new Node("b", a),
c = new Node("c", b);
a.next = c;
}//end of scope
//...other code
a
, b
, and c
should be garbage collected, but they are all being referenced by other objects. How does the Java garbage collection deal with this? (or is it simply a memory drain?)
Source: (StackOverflow)
When I run 'git gui' I get a popup that says
This repository currently has approximately 1500 loose objects.
It then suggests compressing the database. I've done this before, and it reduces the loose objects to about 250, but that doesn't suppress the popup. Compressing again doesn't change the number of loose objects.
Our current workflow requires significant use of 'rebase' as we are transitioning from Perforce, and Perforce is still the canonical SCM. Once Git is the canonical SCM, we will do regular merges, and the loose objects problem should be greatly mitigated.
In the mean time, I'd really like to make this 'helpful' popup go away.
Source: (StackOverflow)
What is JavaScript garbage collection? What's important for a web programmer to understand about JavaScript garbage collection, in order to write better code?
Source: (StackOverflow)
Is it possible to force garbage collection in Java, even it is tricky to do? I know about System.gc();
and Runtime.gc();
but they only suggest to do GC. How can I force GC?
Source: (StackOverflow)
Since Java 7 is going to use the new G1 garbage collection by default is Java going to be able to handle an order of magnitude larger heap without supposed "devastating" GC pause times? Has anybody actually implemented G1 in production, what were your experiences?
To be fair the only time I have seen really long GC pauses is on very large heaps, much more than a workstation would have. To clarify my question; will G1 open the gateway to heaps in the hundreds of GB? TB?
Source: (StackOverflow)
Is there a way to free memory in Java, similar to C's free()
function? Or is setting the object to null and relying on GC the only option?
Source: (StackOverflow)
What is the sampling time JVM uses to throw 'java.lang.OutOfMemoryError : GC overhead limit exceeded'?
I know you can control 98% and 2% with parameters GCTimeLimit and GCHeapFreeLimit but whats the sampling time?
Source: (StackOverflow)
Could you C++ developers please give us a good description of what RAII is, why it is important, and whether or not it might have any relevance to other languages?
I do know a little bit. I believe it stands for "Resource Acquisition is Initialization". However, that name doesn't jive with my (possibly incorrect) understanding of what RAII is: I get the impression that RAII is a way of initializing objects on the stack such that, when those variables go out of scope, the destructors will automatically be called causing the resources to be cleaned up.
So why isn't that called "using the stack to trigger cleanup" (UTSTTC:)? How do you get from there to "RAII"?
And how can you make something on the stack that will cause the cleanup of something that lives on the heap? Also, are there cases where you can't use RAII? Do you ever find yourself wishing for garbage collection? At least a garbage collector you could use for some objects while letting others be managed?
Thanks.
Source: (StackOverflow)
What are the "best practices" for creating (and releasing) millions of small objects?
I am writing a chess program in Java and the search algorithm generates a single "Move" object for each possible move, and a nominal search can easily generate over a million move objects per second. The JVM GC has been able to handle the load on my development system, but I'm interested in exploring alternative approaches that would:
- Minimize the overhead of garbage collection, and
- reduce the peak memory footprint for lower-end systems.
A vast majority of the objects are very short-lived, but about 1% of the moves generated are persisted and returned as the persisted value, so any pooling or caching technique would have to provide the ability to exclude specific objects from being re-used.
I don't expect fully-fleshed out example code, but I would appreciate suggestions for further reading/research, or open source examples of a similar nature.
Source: (StackOverflow)
Start with these simple classes...
Let's say I have a simple set of classes like this:
class Bus
{
Driver busDriver = new Driver();
}
class Driver
{
Shoe[] shoes = { new Shoe(), new Shoe() };
}
class Shoe
{
Shoelace lace = new Shoelace();
}
class Shoelace
{
bool tied = false;
}
A Bus
has a Driver
, the Driver
has two Shoe
s, each Shoe
has a Shoelace
. All very silly.
Add an IDisposable object to Shoelace
Later I decide that some operation on the Shoelace
could be multi-threaded, so I add an EventWaitHandle
for the threads to communicate with. So Shoelace
now looks like this:
class Shoelace
{
private AutoResetEvent waitHandle = new AutoResetEvent(false);
bool tied = false;
// ... other stuff ..
}
Implement IDisposable on Shoelace
Buit now FxCop will complain: "Implement IDisposable on 'Shoelace' because it creates members of the following IDisposable types: 'EventWaitHandle'."
Okay, I implement IDisposable
on Shoelace
and my neat little class becomes this horrible mess:
class Shoelace : IDisposable
{
private AutoResetEvent waitHandle = new AutoResetEvent(false);
bool tied = false;
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Shoelace()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (waitHandle != null)
{
waitHandle.Close();
waitHandle = null;
}
}
// No unmanaged resources to release otherwise they'd go here.
}
disposed = true;
}
}
Or (as pointed out by commenters) since Shoelace
itself has no unmanaged resources, I might use the simpler dispose implementation without needing the Dispose(bool)
and Destructor:
class Shoelace : IDisposable
{
private AutoResetEvent waitHandle = new AutoResetEvent(false);
bool tied = false;
public void Dispose()
{
if (waitHandle != null)
{
waitHandle.Close();
waitHandle = null;
}
GC.SuppressFinalize(this);
}
}
Watch in horror as IDisposable spreads
Right that's that fixed. But now FxCop will complain that Shoe
creates a Shoelace
, so Shoe
must be IDisposable
too.
And Driver
creates Shoe
so Driver
must be IDisposable
.
and Bus
creates Driver
so Bus
must be IDisposable
and so on.
Suddenly my small change to Shoelace
is causing me a lot of work and my boss is wondering why I need to checkout Bus
to make a change to Shoelace
.
The Question
How do you prevent this spread of IDisposable
, but still ensure that your unmanaged objects are properly disposed?
Source: (StackOverflow)