18
When to use the methods System.gc()
and finalize()
? I read that it is very useful in object orientation to destroy memory objects that are not being referenced and to finish tasks, but I see few programmers using.
Example used, taken from the Java book Programmer’s Guide 2nd edition.
package OrientacaoObjetos;
public class Objeto {
private static int instancias = 0;
private int id;
public Objeto() {
id = instancias++;
System.out.println("Objeto.Objeto() [id=" + id + "]");
}
public static int getInstancias() { return instancias; }
public int getId() { return id; }
@Override
public void finalize() {
instancias--;
System.out.println("Objeto.finalize() [id=" + id+ "]");
}
}
package OrientacaoObjetos;
public class TesteGC {
public static void main(String[] args) {
System.out.println("Instancias = " + Objeto.getInstancias());
for (int i = 0; i < 10; i++) {
Objeto o = new Objeto();
}
System.out.println("Instancias = " + Objeto.getInstancias());
System.gc();
System.out.println("Instancias = " + Objeto.getInstancias());
}
}
The book is Java Programmer’s Guide 2edit.
– user28265
You have quoted in your question the passage that says this. I will exorcise the book :D
– Maniero
@bigown, has experienced memory management problems?
– Wellington Avelino
@Wellingtonavelino depends on which, I’ve been through several, but each has its own peculiarity.
– Maniero
@bigown, example: 100% CPU on server or outOfMemory
– Wellington Avelino
@Wellingtonavelino 100% CPU is no memory management problem. I’ve had outOfMemory but not in Java. I’ve never programmed in real Java :D
– Maniero
hahaha, got it! @bigown
– Wellington Avelino