Benjamin Bettan
Benjamin Bettan

Reputation: 91

Java garbage collector - how can I be sure that it has been executed

I have to parse a 3 giga xml file and generate an altered one with SAX.

To do it I'm using serialized objects, one thread.

First tests are great with small files. But with a 3 giga file it will generate a lot of unused instances.

I want to be sure that garbage collector has been executed.

My ideas :

if(...)
{
  for (int i = 0; i < 100; i++) 
  {
            System.gc();
  }
}

or another idea :

if(...)
  {
    Thread.sleep(1 800 000);//30mn
    for (int i = 0; i < 50; i++) {
                System.gc();
            }
    Thread.sleep(1 800 000);//30mn
    for (int i = 0; i < 50; i++) {
                System.gc();
            }
  }

I don't know many things about java garbage collector... What do you think about it ?

Upvotes: 0

Views: 75

Answers (1)

davidxxx
davidxxx

Reputation: 131346

I want to be sure that garbage collector has been executed.

System.gc(); may have some delays before that the GC acts.

Generally, you should not need to invoke System.gc();, overall if you have some pauses between processings as in your sample code.
If you don't do pause between big processings, invoking System.gc(); may make sense but still you should do some benchmark to check whether if is really required and that it doesn't create on the contrary slow downs.

Besides, invoking System.gc(); will be helpless if the objects that you want to free are not eligible to be.

But with a 3 giga file it will generate a lot of unused instances.

You don't show code but unused instances don't mean necessarily instances not referenced any longer by living objects.

The GC collects and sweeps only objects that are eligible to be : that is objects that are not referenced any longer by any living object.
To do it, you have to focus on reducing the scope of the objects that you manipulate to make it as short as required.

Upvotes: 1

Related Questions