Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

## Discussion 5 - Nazli Dokuzoglu

Nazli Dokuzoglu
902163737
gth795k
Discussion 5

Garbage Collection

1) What is “Garbage Collection”?

Garbage collection is recycling an object that is no longer referenced by the program to make the space, used by the unreferenced object, available for the new object.
In Squeak, garbage collection is handled by virtual machine.

2) What are the advantages of garbage collection?
• Garbage collection relieves the programmer from the burden of freeing allocated memory thus reducing the memory problems and the time spend on those problems in the program.
• Garbage collection helps to ensure program integrity. Since the programmers are not allowed to free memory incorrectly, the programs are more secure.

3) What are the disadvantages of garbage collection?
• Garbage collection may affect the performance of the program since the virtual machine has to keep track of the objects being referenced by the program and free the unreferenced ones which take more CPU time.
• Programmers have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.

Garbage Collection Algorithms

4) Explain two garbage collection algorithms, Reference Counting and Mark-Sweep, briefly.

Reference Counting Algorithm
When an object is first created and a reference to it is assigned to a variable, the object's reference count is set to one. When any other variable is assigned a reference to that object, the object's count is incremented. When a reference to an object goes out of scope or is assigned a new value, the object's count is decremented. Any object with a reference count of zero can be garbage collected. When an object is garbage collected, any objects that it refers to have their reference counts decremented.
Mark-Sweep Algorithm
• Mark all the nodes as 0.
• Find the root nodes and turn them into 1.
• Find a node marked as 1 and turn it into 2, change all of the nodes that it points to 1.
• Repeat 3rd step until there are no nodes marked as 1.
• Garbage collect the nodes marked as 0.

6) What is the problem with each algorithm? Give an example.
Reference Counting Algorithm cannot detect cycles (objects pointing to each other).
The two objects that are pointing to each other will never have a count equal to zero, so they will not be garbage collected but they may be unreachable by the root nodes of the program.
In Mark-Sweep Algorithm some of the objects need to be finalized before garbage collected so they require two garbage collection cycles. An example for this can be network sockets, they should be closed first and then garbage collected.

5) Which of the nodes need to be garbage collected according to the Mark-Sweep algorithm?

C and G

References
http://www.artima.com/insidejvm/ed2/gcP.html