Java Reference
In-Depth Information
the same time, one of them will have to wait for the other to finish. If one of them doesn't
wait, the resource may get corrupted. Let's look at a specific example. Consider the run()
method of Examples 3-1 and 3-2 . As previously mentioned, the method builds the result
as a String , and then prints the String on the console using one call to Sys
tem.out.println() . The output looks like this:
Triangle.java: B4C7AF1BAE952655A96517476BF9DAC97C4AF02411E40DD386FECB58D94CC769
InterfaceLister.java: 267D0EFE73896CD550DC202935D20E87CA71536CB176AF78F915935A6
Squares.java: DA2E27EA139785535122A2420D3DB472A807841D05F6C268A43695B9FDFE1B11
UlpPrinter.java: C8009AB1578BF7E730BD2C3EADA54B772576E265011DF22D171D60A1881AFF51
Four threads run in parallel to produce this output. Each writes one line to the console.
The order in which the lines are written is unpredictable because thread scheduling is
unpredictable, but each line is written as a unified whole. Suppose, however, you used
this variation of the run() method, which, rather than storing intermediate parts of the
result in the String variable result , simply prints them on the console as they become
available:
@Override
public void run () {
try {
FileInputStream in = new FileInputStream ( filename );
MessageDigest sha = MessageDigest . getInstance ( "SHA-256" );
DigestInputStream din = new DigestInputStream ( in , sha );
while ( din . read () != - 1 ) ; // read entire file
din . close ();
byte [] digest = sha . digest ();
System . out . print ( input + ": " );
System . out . print ( DatatypeConverter . printHexBinary ( digest ));
System . out . println ();
} catch ( IOException ex ) {
System . err . println ( ex );
} catch ( NoSuchAlgorithmException ex ) {
System . err . println ( ex );
}
}
When you run the program on the same input, the output looks something like this:
Triangle.java: B4C7AF1BAE952655A96517476BF9DAC97C4AF02411E40DD386FECB58D94CC769
InterfaceLister.java: Squares.java: UlpPrinter.java:
C8009AB1578BF7E730BD2C3EADA54B772576E265011DF22D171D60A1881AFF51
267D0EFE73896CD550DC202935D20E87CA71536CB176AF78F915935A6E81B034
DA2E27EA139785535122A2420D3DB472A807841D05F6C268A43695B9FDFE1B11
The digests of the different files are all mixed up! There's no telling which number
belongs to which digest. Clearly, this is a problem.
The reason this mix-up occurs is that System.out is shared between the four different
threads. When one thread starts writing to the console through several
System.out.print() statements, it may not finish all its writes before another thread
Search WWH ::




Custom Search