Java Reference
In-Depth Information
@Override
public String toString () {
String result = filename + ": " ;
if ( digest != null ) {
result += DatatypeConverter . printHexBinary ( digest );
} else {
result += "digest not available" ;
}
return result ;
}
public static void main ( String [] args ) {
for ( String filename : args ) {
// Calculate the digest
InstanceCallbackDigestUserInterface d
= new InstanceCallbackDigestUserInterface ( filename );
d . calculateDigest ();
}
}
}
Using instance methods instead of static methods for callbacks is a little more compli‐
cated but has a number of advantages. First, each instance of the main class ( Instance
CallbackDigestUserInterface , in this example) maps to exactly one file and can keep
track of information about that file in a natural way without needing extra data struc‐
tures. Furthermore, the instance can easily recalculate the digest for a particular file, if
necessary. In practice, this scheme proves a lot more flexible. However, there is one
caveat. Notice the addition of the calculateDigest() method to start the thread. You
might logically think that this belongs in a constructor. However, starting threads in a
constructor is dangerous, especially threads that will call back to the originating object.
There's a race condition here that may allow the new thread to call back before the
constructor is finished and the object is fully initialized. It's unlikely in this case, because
starting the new thread is the last thing this constructor does. Nonetheless, it's at least
theoretically possible. Therefore, it's good form to avoid launching threads from con‐
structors.
The first advantage of the callback scheme over the polling scheme is that it doesn't
waste so many CPU cycles. However, a much more important advantage is that callbacks
are more flexible and can handle more complicated situations involving many more
threads, objects, and classes. For instance, if more than one object is interested in the
result of the thread's calculation, the thread can keep a list of objects to call back. Par‐
ticular objects can register their interest by invoking a method in the Thread or Runna
ble class to add themselves to the list. If instances of more than one class are interested
in the result, a new interface can be defined that all these classes implement. The
interface would declare the callback methods.
Search WWH ::




Custom Search