0

Consider the following contrived example:

1 public class Example
2 {
3     static CountryList countryList = new CountryList();
4
5     public void DoWork(ShoppingCart cart)
6     {
7           Method1();
8
9           Method2();
10
11          cart.DoSomething();
12    }
13
14    private void Method1()
15    {
16        var person = new Person();
17    }
18
19    private void Method2()
20    {
21        var order = new Order();
22    }
23 }

In the above example, let's say currently Method2 is being executed and when the CLR is trying to allocate memory for the call to new Order(), it finds that GC needs to be run.

Please correct me if I am wrong about the following:

  • Garbage collector suspend all activity at line # 21 and kick starts a collection and once it's done, it continues with line #21 etc.?
  • When garbage collector suspends all activity at line # 21, how does it find the GC roots? Are these roots found my the current callstack? i.e does GC walk up the current callstack and find roots?
    For example: I think the roots in the above program would be 'order', 'cart' and 'countryList'. At this point if GC is run the only object that is collected is the one referred by 'person' as its unreachable. Am I right about this?
Kiran
  • 56,921
  • 15
  • 176
  • 161
  • 1
    Did you read [this](http://stackoverflow.com/questions/8458886/what-is-a-rooted-reference)? – Yuval Itzchakov Nov 02 '15 at 07:35
  • @YuvalItzchakov: Yup, I actually read it but was looking from a example point of view as the other thread has more theory – Kiran Nov 02 '15 at 07:39
  • Why would it continue with line #20 if it already was at line #21? Anyway, this is a duplicate of the question @YuvalItzchakov linked to, it answers this question as well. In this case theory should match practice, and if practice differs from theory it is undocumented. – Lasse V. Karlsen Nov 02 '15 at 07:40
  • @LasseV.Karlsen: good catch...that was a mistake. – Kiran Nov 02 '15 at 07:42
  • @LasseV.Karlsen: How about the second question?...can you clarify regarding it? – Kiran Nov 02 '15 at 07:44
  • The duplicate question answers this as well. Any local variables in methods that are currently running, meaning that it will walk the callstack. `countryList` is a static field, `cart` is passed in as a parameter and is used after the method calls, and `order` is currently being allocated (which provoked the garbage collection cycle). – Lasse V. Karlsen Nov 02 '15 at 07:45
  • Thanks! @LasseV.Karlsen – Kiran Nov 02 '15 at 14:00

0 Answers0