Skip to main content

Garbage Collection Test

4 replies [Last post]
ateslin
Offline
Joined: 2005-11-04

Hi,

I am trying to test garbage collection. To start with i am using book O'Reilly - "Java Performance Tunning". In it i found the code below. But when I comment out //s=null and //v=null the time results are the same as with initialising them to null.

Any ideas?
Im I missing some aspects here?

import java.util.*;

public class GarbageTest
{

public static void main(String[] args) {

int SIZE = 40000;
StringBuffer s;
Vector v;

for(int i = 0; i < SIZE; i++) {
s = new StringBuffer(50);
v = new Vector(30);
s.append(i).append(i+1).append(i+2).append(i+3);
}

s = null;
v = null;
System.out.println("Sarting Garbage collection");
long time = System.currentTimeMillis();
System.gc();
long after = System.currentTimeMillis()-time;
System.out.println("Garbage collection took " +
after + " millis");

int[] arr = new int[SIZE*10];
time = System.currentTimeMillis();
arr = null;
System.out.println("Sarting Garbage collection");
System.gc();
after = System.currentTimeMillis()-time;
System.out.println("Garbage collection took " +
after + " millis");

}

}

Thank you

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
alexlamsl
Offline
Joined: 2004-09-02

that's what I would expect - the time difference with a pair of objects out of 2x40000 would be tiny ;)

but obviously setting them to null is just for concrete correctness~

ateslin
Offline
Joined: 2005-11-04

But setting them to null shouldn't be garbage collected all those 2*40000 objects?

alexlamsl
Offline
Joined: 2004-09-02

no, of course not - how is an assignment statement that overwrites the previous pointer reference (s = new ...; v = new ...) going to leave the previous object still strongly referenced? :)

ateslin
Offline
Joined: 2005-11-04

Oh, yes of course. Thanks for that