Java Reference
In-Depth Information
}
Solution 82: Beer blast
If you run the program with the command line argument slave , it prints a stirring rendition of that
classic childhood ditty, "99 Bottles of Beer on the Wall"— there's no mystery there. If you run it
with no command line argument, it starts a slave process that prints the ditty, but you won't see the
output of the slave process. The main process waits for the slave process to finish and then prints
the exit value of the slave. By convention, the value 0 indicates normal termination, so that is what
you might expect the program to print. If you ran it, you probably found that it just hung there,
printing nothing at all. It's as if the slave process were taking forever. Although it might feel like it
takes forever to listen to "99 Bottles of Beer on the Wall," especially if it is sung out of tune, the
song has "only" 99 verses. Besides, computers are fast, so what's wrong with the program?
The clue to this mystery is in the documentation for the Process class, which says: "Because some
native platforms only provide limited buffer size, failure to promptly read the output stream of the
subprocess may cause the subprocess to block, and even deadlock" [Java-API] . That is exactly
what's happening here: There is insufficient space in the buffer to hold the interminable ditty. To
ensure that the slave process terminates, the parent must drain its output stream, which is an input
stream from the perspective of the master. The following utility method performs this task in a
background thread:
static void drainInBackground(final InputStream is) {
new Thread(new Runnable() {
public void run() {
try {
while(is.read() >= 0) ;
} catch (IOException e) {
// return on IOException
}
}
}).start();
}
 
 
Search WWH ::




Custom Search