O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Multiplexed Network Client

We end this chapter with Example 6-14, a complex class named HttpDownloadManager. As its name implies, this class is a client-side utility that manages any number of concurrent HTTP downloads on a background thread. To download something, just call the download( ) method, passing a java.net.URI and an optional Listener object to be notified when the download is complete or has aborted with an error. download( ) does not block: it returns a Download object immediately, and you can monitor the status of the download by polling the methods of this object. The data that is downloaded is not saved to a file, but is available from the getData( ) method of the Download object.

The Listener and Download interfaces are defined as inner classes of HttpDownloadManager. The Status class is another inner class: it is a type-safe enumeration of download states returned by Download.getStatus( ). Two other inner classes used in this example are DownloadImpl, the package-private concrete implementation of the Download interface, and Test, a simple test program that demonstrates the usage of the HttpDownloadManager.

HttpDownloadManager extends Thread, and the downloads are handled in this background thread. Multiple downloads can be handled concurrently (this is useful when the client has more bandwidth available than the servers which are being downloaded from) because the thread uses a Selector to multiplex the SocketChannel objects from which data is being read: the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required