Java Reference
In-Depth Information
OutputStream out = new BufferedOutputStream (
new GZIPOutputStream (
new FileOutputStream ( output )));
) {
int b ;
while (( b = in . read ()) != - 1 ) out . write ( b );
out . flush ();
} catch ( IOException ex ) {
System . err . println ( ex );
}
}
}
}
}
Notice the use of Java 7's try-with-resources statement in GZipRunnable . Both the input
and output stream are declared at the beginning of the try block and automatically
closed at the end of the try block.
Also notice the buffering of both input and output. This is very important for perfor‐
mance in I/O-limited applications, and especially important in network programs. At
worst, buffering has no impact on performance, while at best it can give you an order
of magnitude speedup or more.
Example 3-14 is the main program. It constructs the pool with a fixed thread count of
four, and iterates through all the files and directories listed on the command line. Each
of those files and files in those directories is used to construct a GZipRunnable . This
runnable is submitted to the pool for eventual processing by one of the four threads.
Example 3-14. The GZipThread user interface class
import java.io.* ;
import java.util.concurrent.* ;
public class GZipAllFiles {
public final static int THREAD_COUNT = 4 ;
public static void main ( String [] args ) {
ExecutorService pool = Executors . newFixedThreadPool ( THREAD_COUNT );
for ( String filename : args ) {
File f = new File ( filename );
if ( f . exists ()) {
if ( f . isDirectory ()) {
File [] files = f . listFiles ();
for ( int i = 0 ; i < files . length ; i ++) {
if (! files [ i ]. isDirectory ()) { // don't recurse directories
Runnable task = new GZipRunnable ( files [ i ]);
pool . submit ( task );
Search WWH ::




Custom Search