The Artima Developer Community
Sponsored Link

Legacy Design Forum
Finalization and Cleanup

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

a coding techniqe that will force cleanup (try/finally)

Posted by Chris Bedford on January 06, 2002 at 11:54 PM


Hi...

I just tried this out and it seems to work... this is a technique that i think you can use when u want to provide
a way for users of your class to ensure an object's cleanup
method is invoked no matter what kind of whacky control
flows (e.g., exceptions) happen....


import java.io.*;
import java.util.*;

public class finx {

int tidied = 0;

finx() {
tidied = 0;
System.out.println("made a finx");
}

void yelp() {
System.out.println("arf arf");
}

void cleanup() {
tidied = 1;
System.out.println("cleanedup");
}

// Here i am using finalize as a debugging technique to catch instances
// when programmers have forgotten to call cleanup. On linux i find
// that i need to call System.runFinalizersOnExit(true) to force the
// finalizer to run... runFinalizersOnExit is deprecated, but this
// just a sanity check anyway.

protected void finalize() {
if (tidied == 0) {
System.out.println("exited with out tidy");
} else {
System.out.println("exited WITH TIDY");
}
}


public static void main(String[] args) {
if (args.length < 1) {
System.out.println(
"Usage: java Words ");
System.exit(1);
}
System.runFinalizersOnExit(true);

finx m = new finx();
finx f = new finx();
try {
if (args[0].substring(0, 1).equals("r")) {
System.out.println("returning");
return;
}
if (args[0].substring(0, 1).equals("e")) {
finx g = null;
g.yelp();
}

System.out.println("end of block");

} finally {
f.cleanup();
}

}
}






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us