The Explicit Object Release pattern suggests that when such an object is no longer needed, the external resources tied up with the object should be released explicitly, in a timely manner.
The Java programming language provides the following two ways to design the mechanism to release external resources explicitly:
- The finalize() method
- The finally statement
The garbage collection process runs periodically to reclaim the memory occupied by objects that are out of scope and no longer referenced.
When the garbage collection process runs, before an object is garbage collected, the Java runtime system invokes the object’s finalize() method.
The finalize() method must be declared as:
protected void finalize() throws Throwable
The Garbage Collection Process Runs as a Low-Level Background Daemon Thread
even though the finalize() method can be used to perform clean-up operations, it is not a reliable option to free system resources in a timely manner. This is mainly because the garbage collection process, which invokes the finalize() method on an object, runs at unpredictable times.
Releasing resources inside the finally block is more advisable as the code inside the finally is always guaranteed to be executed even when there is an unexpected runtime exception.
public class OrderLog {public void log(Order order) {PrintWriter dataOut = null;try {dataOut =new PrintWriter(new FileWriter("order.txt"));String dataLine =order.getID() + "," + order.getItem() +"," + order.getQty();dataOut.println(dataLine);dataOut.close(); //duplicate code} catch (IOException e) {System.err.println("IOException Occurred: ");}catch (NullPointerException ne) {System.err.println("NullPointerException Occurred: ");}finally { //Guaranteed to get executedif (dataOut != null) {dataOut.close();}}}}
the code implementation to close the PrintWriter object inside the finally statement is guaranteed to always get executed. That means, even if an uncaught runtime exception occurs, the PrintWriter object will still be closed as a result of executing the finally statement code.
No comments:
Post a Comment