Dado que existe una incertidumbre en la llamada del método finalize () por JVM (no estoy seguro de si se ejecutará o no finalize () que se anula), para fines de estudio, la mejor manera de observar lo que sucede cuando se llama a finalize () es obligar a la JVM a llamar a la recolección de basura por comando System.gc()
.
Específicamente, se llama a finalize () cuando un objeto ya no está en uso. Pero cuando intentamos llamarlo creando nuevos objetos, no hay certeza de su llamada. Entonces, con certeza, creamos un null
objeto c
que obviamente no tiene uso futuro, por lo tanto, vemos la c
llamada de finalización del objeto .
Ejemplo
class Car {
int maxspeed;
Car() {
maxspeed = 70;
}
protected void finalize() {
// Originally finalize method does nothing, but here we override finalize() saying it to print some stmt
// Calling of finalize is uncertain. Difficult to observe so we force JVM to call it by System.gc(); GarbageCollection
System.out.println("Called finalize method in class Car...");
}
}
class Bike {
int maxspeed;
Bike() {
maxspeed = 50;
}
protected void finalize() {
System.out.println("Called finalize method in class Bike...");
}
}
class Example {
public static void main(String args[]) {
Car c = new Car();
c = null; // if c weren`t null JVM wouldn't be certain it's cleared or not, null means has no future use or no longer in use hence clears it
Bike b = new Bike();
System.gc(); // should clear c, but not b
for (b.maxspeed = 1; b.maxspeed <= 70; b.maxspeed++) {
System.out.print("\t" + b.maxspeed);
if (b.maxspeed > 50) {
System.out.println("Over Speed. Pls slow down.");
}
}
}
}
Salida
Called finalize method in class Car...
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51Over Speed. Pls slow down.
52Over Speed. Pls slow down.
53Over Speed. Pls slow down.
54Over Speed. Pls slow down.
55Over Speed. Pls slow down.
56Over Speed. Pls slow down.
57Over Speed. Pls slow down.
58Over Speed. Pls slow down.
59Over Speed. Pls slow down.
60Over Speed. Pls slow down.
61Over Speed. Pls slow down.
62Over Speed. Pls slow down.
63Over Speed. Pls slow down.
64Over Speed. Pls slow down.
65Over Speed. Pls slow down.
66Over Speed. Pls slow down.
67Over Speed. Pls slow down.
68Over Speed. Pls slow down.
69Over Speed. Pls slow down.
70Over Speed. Pls slow down.
Nota - Incluso después de imprimir hasta 70 y después de lo cual el objeto b no se está utilizando en el programa, existe la incertidumbre de que b sea borrado o no por JVM ya que "Método de finalización llamado en la clase Bike ..." no se imprime.