Checksum: an interface for monitoring streams in Java

Consider a case where you want to monitor the data passing through a stream. Typically you’d subclass the FilterInputStream or FilterOutputStream class for that, but sometimes it would be more convenient to implement an interface instead.

The CheckedInputStream and CheckedOutputStream utility classes in the java.util.zip package can be used for this. They act as stream decorators that send all passing bytes to a given Checksum instance. The Checksum interface is primarily designed for calculating and accessing checksums like is done in the CRC32 and Adler32 implementations, but you could just as well use the interface for other kinds of stream tracking.

I came up with this trick when looking for a way to implement a minimal watchdog timer that can monitor activity in both input and output streams. The code was for a special bootstrap class loader where I needed to minimize the number of separate implementation classes, which is why the Checksum interface and the existing stream decorator classes came in so handy!