• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collector implementation

 
Nilesh Dhiman
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that implementing a garbage collector in a java program is a bad practice. But if we want to implement this logic in our code then how is it possible ?
 
salvin francis
Bartender
Posts: 1268
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am not entirely sure what you want,


There is a method called :



You can call this method any time to suggest the jvm to perform garbage collection.
Note that the act of garbage collection is a memory intensive operation use it sparingly.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe Nilesh means that calling System.gc(); in a program is usually not a good idea, and he's right. Normally you should just leave garbage collection up to the JVM. Only add calls like System.gc(); if you are sure that you know what you are doing, and if you know that it solves a problem (don't do it just because you have a vague feeling that it's a good idea).

The built-in garbage collector of the JVM is very smart and usually knows better than you yourself when and how to cleanup objects.
 
Nilesh Dhiman
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes we can call the System.gc() explicitly in our code. But what if we want to create our own garbage collection function. I mean that how can we collect all those objects in our program which are no longer used or referenced by other variables; and then release the memory occupied by those objects.Here we have to use some kind of destructor logic (which is not avaiable in java) .
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't write your own garbage collector inside your own Java program. Garbage collection is part of the internals of the JVM, and there is not much that you can (or should, normally) do with the garbage collection inside your Java program. Why do you want to interfere with the garbage collection process, how do you think this will make your program run better? Is your program having memory problems?

Why are you calling System.gc() in your own program? Did you add it just because you think it would be a good idea, or did you actually measure the memory usage of your program using a profiler?

If you want to tune garbage collection, search for "java garbage collection tuning".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic