Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Pipes are used to channel the output from one thread into the input of another.PipedReader
andPipedWriter
(and their input and output stream counterpartsPipedInputStream
andPipedOutputStream
) implement the input and output components of a pipe. Why is this useful?Consider a class that implements various string manipulation utilities, such as sorting and reversing text. It would be nice if the output of one of these methods could be used as the input for another so that you could string a series of method calls together to perform a higher-order function. For example, you could reverse each word in a list, sort the words, and then reverse each word again to create a list of rhyming words.
Without pipe streams, the program would have to store the results somewhere (such as in a file or in memory) between each step, as shown here:
With pipe streams, the output from one method could be piped into the next, as shown in this figure: Let's look at a program, called RhymingWords
, that implements what's represented in the previous figure. This program usesPipedReader
andPipedWriter
to connect the input and output of itsreverse
andsort
methods to create a list of rhyming words. Several classes make up this program.First, let's look at the calling sequence of the
reverse
andsort
methods from themain
method:The innermost call toFileReader words = new FileReader("words.txt"); Reader rhymingWords = reverse(sort(reverse(words)));reverse
takes aFileReader
, which is opened on the filewords.txt
which contains a list of words. The return value ofreverse
is passed tosort
, whose return value is then passed to another call toreverse
.Let's look at the
reverse
method; thesort
method is similar and you will understand it once you understandreverse
.The statements in boldface create both ends of a pipe--apublic static Reader reverse(Reader src) throws IOException { BufferedReader in = new BufferedReader(source); PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); PrintWriter out = new PrintWriter(pipeOut); new ReverseThread(out, in).start(); return pipeIn; }PipedWriter
and aPipedReader
-- and connect them by constructing thePipedReader
"on" thePipedWriter
. Whatever is written to thePipedWriter
can be read from thePipedReader
. The connection forms a pipe, as illustrated here:The reverse
method starts aReverseThread
that writes its output to thePipedWriter
and then returns thePipedReader
to the caller. The caller then arranges for a sorting thread to read from it. Thesort
method is exactly the same, except that it creates and starts aSortThread
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.