Chapter 4, Exercise 13
Ok, here is some more fun with finalizers, despite what I mentioned on Thursday (David Chess' paraphrasing of Joshua Bloch's glowing description of finalizers: "Finalizers are lousy; avoid them in essentially all cases.") The THECLAPP solution for this one is pretty straightforward. My first Scala attempt was not as clean, because I assumed that the fact that the word "finalizer" didn't show up anywhere in the Scala manual meant that finalizers wouldn't work in Scala. So I made a java base class with a finalizer that called a method "my_finalize", and made a scala class that inherited from that java base class, and had an override defined for my_finalize. That all worked just fine, but then I tried it the following simpler way, and it Just Worked too.
package x;
class c4x13fc {
var i : Int = _;
var filled : Boolean = false;
def this(ci: Int) = {
this();
Console.println( "c4x13fc::Tank " +ci+ " init." );
i = ci;
}
override def finalize () = {
if (filled) {
Console.println( "Error: tank " +i+ " not empty at finalize!" );
}
else {
Console.println( "Ok, tank " +i+ " is empty at finalize." );
}
}
}
object c4x13f {
def testTanks = {
{ // case 1: tank created, filled, emptied, thrown away
val tank = new c4x13fc(0);
tank.filled = true;
tank.filled = false;
}
{ // case 2: tank created, filled, thrown away
val tank = new c4x13fc(1);
tank.filled = true;
}
{ // case 3: tank created & thrown away
new c4x13fc(2);
}
}
def main ( args: Array[String] ) = {
testTanks;
System.gc();
}
}
1:54:31 PM