Java Reference
In-Depth Information
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 ++) {
// Now print the result
StringBuffer result = new StringBuffer ( args [ i ]);
result . append ( ": " );
byte [] digest = digests [ i ]. getDigest ();
result . append ( DatatypeConverter . printHexBinary ( digest ));
System . out . println ( result );
}
}
If you're lucky, this will work and you'll get the expected output, like this:
D:\JAVA\JNP4\examples\03> java ReturnDigest2 *.java
AccumulatingError.java: 7B261F7D88467A1D30D66DD29EEEDE495EA16FCD3ADDB8B613BC2C5DC
BenchmarkScalb.java: AECE2AD497F11F672184E45F2885063C99B2FDD41A3FC7C7B5D4ECBFD2B0
CanonicalPathComparator.java: FE0AACF55D331BBF555528A876C919EAD826BC79B659C489D62
Catenary.java: B511A9A507B43C9CDAF626D5B3A8CCCD80149982196E66ED1BFFD5E55B11E226
...
However, let me emphasize that point about being lucky . You may not get this output.
In fact, you may still get a NullPointerException . Whether this code works is com‐
pletely dependent on whether every one of the ReturnDigest threads finishes before
its getDigest() method is called. If the first for loop is too fast and the second for loop
is entered before the threads spawned by the first loop start finishing, you're back where
you started. Worse yet, the program may appear to hang with no output at all, not even
a stack trace.
Whether you get the correct results, an exception, or a hung program depends on many
factors, including how many threads the program spawns, the speed of the CPU and
disk on the system where this is run, how many CPUs the system uses, and the algorithm
the Java virtual machine uses to allot time to different threads. This is called a race
condition . Getting the correct result depends on the relative speeds of different threads,
and you can't control those! You need a better way to guarantee that the getDigest()
method isn't called until the digest is ready.
Search WWH ::




Custom Search