|
2.14.7 Disposing of Exprs
We have seen the dispose() method used frequently in this discussion of the Expr class. An Expr object might make use of a loopback MathLink internally, and any time a Java class holds such a non-Java resource it is important to provide programmers with a dispose() method that causes the resource be released. Although the finalizer for the Expr class will call dispose(), you cannot rely on the finalizer ever being called. Although it is good style to always call dispose() on an Expr when you are finished using it, you should know that many of the operations you can perform on an Expr will cause it to be "unwound" off its internal loopback link and cause that link to be closed. After this happens, the dispose() method is unnecessary. Calling the toString() method is an example of an operation that makes dispose() unnecessary, and in fact virtually any operation that queries the structure of an Expr or extracts a part will have this effect. This is useful to know since it allows shorthand code like this:
System.out.println("the result was " + ml.getExpr().toString());
instead of the more verbose:
Expr e = ml.getExpr();
System.out.println("the result was " + e.toString());
e.dispose();
You should get in the habit of calling dispose() explicitly on Expr objects. In cases where it is inconvenient to store an Expr in a named variable, and you know that the Expr does not need to be disposed, then you can skip calling it.
Because extracting any piece of an existing expression will make dispose() unnecessary, you do not have to worry about calling dispose() on Exprs that are obtained as parts of another one:
Expr e = ml.getExpr();
// The moment that head() or part() are called on e below, you know that neither
// e, e2, nor e3 need to be disposed.
Expr e2 = e.head();
Expr e3 = e.part(1);
You cannot reliably use an Expr object after dispose() has been called on it. We have already seen that dispose() is often unnecessary because many Exprs have already had their internal loopback links closed. For any such Exprs, dispose() will have no effect at all and there would be no problem continuing to use the Expr after dispose() had been called. That being said, it is horrible style to ever try to use an Expr after calling dispose(). A call to dispose() should always be an unambiguous indicator that you have no further use for the given Expr or any part of it.
|