Java Reference
In-Depth Information
Polling
The solution most novices adopt is to make the getter method return a flag value (or
perhaps throw an exception) until the result field is set. Then the main thread period‐
ically polls the getter method to see whether it's returning something other than the flag
value. In this example, that would mean repeatedly testing whether the digest is null
and using it only if it isn't. For example:
public static void main ( String [] args ) {
ReturnDigest [] digests = new ReturnDigest [ args . length ];
for ( int i = 0 ; i < args . length ; i ++) {
// Calculate the digest
digests [ i ] = new ReturnDigest ( args [ i ]);
digests [ i ]. start ();
}
for ( int i = 0 ; i < args . length ; i ++) {
while ( true ) {
// Now print the result
byte [] digest = digests [ i ]. getDigest ();
if ( digest != null ) {
StringBuilder result = new StringBuilder ( args [ i ]);
result . append ( ": " );
result . append ( DatatypeConverter . printHexBinary ( digest ));
System . out . println ( result );
break ;
}
}
}
}
This solution may work. If it works at all, it gives the correct answers in the correct order
irrespective of how fast the individual threads run relative to each other. However, it's
doing a lot more work than it needs to.
Worse yet, this solution is not guaranteed to work. On some virtual machines, the main
thread takes all the time available and leaves no time for the actual worker threads. The
main thread is so busy checking for job completion that there's no time left to actually
complete the job! Clearly this isn't a good approach.
Callbacks
In fact, there's a much simpler, more efficient way to handle the problem. The infinite
loop that repeatedly polls each ReturnDigest object to see whether it's finished can be
eliminated. The trick is that rather than having the main program repeatedly ask each
ReturnDigest thread whether it's finished (like a five-year-old repeatedly asking, “Are
we there yet?” on a long car trip, and almost as annoying), you let the thread tell the
Search WWH ::




Custom Search