GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Sunday 23 May 2004
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   comment/     


Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/2/6; 12:39:40 .
Click here to send an email to the editor of this weblog.

May 2004
Sun Mon Tue Wed Thu Fri Sat
            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          
Apr   Jun

Previous/Next