Reprint please indicate source: http://www.cnblogs.com/lighten/p/7056278.html
1. Preface
This chapter describes the last pair of byte streams in the IO architecture of Java-pipeline flow. Previously in the byte array stream when said, it can act as the input and output stream conversion, Java also has a pipeline flow can do similar functions, but its main role is used for communication between different threads, the following is specific about how the pipeline flow is implemented, and related examples.
It is important to note that in the JDK source notes, it is common to use a pipeline output stream to correlate a pipeline input into a pipeline session. Typically, the input and output streams are not in one thread, and can cause deadlocks if used in the same thread. When data cannot be read from the input stream, the output stream is interrupted.
2.PipedOutputStream
Pipeline output flow is very simple, its inheritance outputstream, the concrete class structure is as follows:
It accepts a pipe input stream, calls the Connect method, and, after passing it, resets the relevant data and assigns values. Of course, you can also directly new a pipeline output stream, and then associate through the Connect method.
The two write methods are not related to the output stream and are manipulated by the input stream.
The Flush method and the Close method are also operated through a pipeline input stream.
The operation of the entire input stream is done through the input stream, so the next step is to focus on what the input stream does.
3.PipedInputStream
There is not much content in this pipeline:
Above is the main content, the input stream has a buffer byte array, the constructor has output stream time to do two things, one is initpipe initialize this buffer, the default size of 1024 bytes, the other is to call the Connect method, The Connect method is actually the call to connect of the output stream, which in turn modifies the related fields of the input stream. If the input stream is constructed without an output stream, it needs to be associated using the Connect method. However, remember that regardless of the input stream initialization and output stream initialization, the Connect method can only be called once by any means, that is, two objects can only be associated with each other one time.
Let's look at what the receive for the input stream called by the output stream write is doing:
The Receive method of the input pipeline stream is called when the pipe stream is output and is eventually written to buffer. Note that when buffer is finished, it resets to write subscript in. Receive an array is also to determine whether the remaining space buffer is sufficient. The Read method reads the contents of this array:
3.1 Deadlock Inquiry
Previously said, if the write and read these two operations are in the same thread may occur deadlock, here specifically how to deadlock, the test code is as follows:
@Testpublic void Test () throws IOException {PipedInputStream PiS = new PipedInputStream (); PipedOutputStream pos = new PipedOutputStream (pis); byte[] read = new byte[10];byte[] Write = new Byte[100];int count = 0;w Hile (True) {pos.write (write);p is.read (read); System.out.println ("Write Read count:" + (++count));}}
The results are as follows:
When the count is 11, it's not going to go down, it's obviously a dead lock. How did this come about? Review the above source code:
When the data is written, the Receive method is called to obtain the PiS object lock. When you finish writing the data, the lock will be released. The Read method also needs to acquire the lock and then release the lock when it is finished. At first glance seems to be no problem ah, should not create a deadlock ah. But the problem is on a method called receive for the Write method Awaitspace. Because the write is faster than the read speed, according to the practice of the source code will cause in the value of the out, and then wait for the input stream to use, because the input stream and the output stream on the same thread, here becomes a dead loop, wait after wait is still waiting for write consumption. Writing faster than reading can also cause wait. The note says that the deadlock does not know if this is the case, and if so, the deadlock feels a bit inappropriate.
3.2 Write read operation description
When the read and write operations are in different threads, the data is written from the pipeline output stream, and the receive method of the pipeline to the inflow is called. There is a cache array buffer that receives the bytes written by the Write method. The input stream has two subscripts, one in is used to mark the number of bytes currently cached, and an out to mark the location where the Read method reads buffer. Write, if in==out, then pause the write, because at this time to determine the write faster read, to prevent the data is overwritten, this time the write thread will hang, waiting for the read thread to read the data. Read thread if read to in==out the write is considered complete, read is completed. The initial in is equal to-1, so the first time it is read, it is also a process of suspending the read thread waiting to be written. The in is only 1 when the read thread has read all the writes. The following paragraph in the read () method, only the first read can enter, because if there is a write in is not less than 0.
The problem is, if the write thread hangs, the read thread reads to the current write location, that is, when the in==out is read, what happens when the reading is completed?
@Testpublic void Test2 () throws IOException, interruptedexception {pipedinputstream pis = new PipedInputStream (); PipedOutputStream pos = new PipedOutputStream (PiS); Countdownlatch latch = new Countdownlatch (2); new Thread (New Runnable () {@Overridepublic void run () {byte[] b = new byte[10 25];B[1024] = 1;try {pos.write (b, 0, 1022); Thread.Sleep (c);p Os.write (b, 1022, b.length);p os.close (); catch (IOException e) {e.printstacktrace ();} catch (Interruptedexception e) {e.printstacktrace ();} finally { Latch.countdown ();}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buf = new byte[1024]; int len = 0; try {byte B; while ((b = (byte) pis.read ())! =-1) {baos.write (b); }} catch (IOException e) {e.printstacktrace ();} Byte[] result = Baos.tobytearray (); System.out.println (ResULt.length + ":" + arrays.tostring (result)); Latch.countdown ();}}). Start (); Latch.await ();}
The result is:
An exception occurs, and only 1022 bytes are read to the first write. This creates a problem in which a batch of data is written, and a batch of data is written, but it is possible to read the embarrassing situation where the first batch ends. Is there any good way to solve this problem? At least I didn't find any good way. It is best to write one at a time when using a pipe flow, and it is best to initialize the buffer size of the pipe stream to the size of the write. Other methods do not completely prevent this phenomenon, but the probability is smaller, such as control read and write speed. If you really want to implement multiple writes and be reliable, the only way I can think of is if the read-write thread is sharing a lock, plus a stream end marker. But this approach also has to be very careful, in the beginning it is easy to create a deadlock, if the read thread first acquires a public lock, the inside of the pipeline to obtain the lock, even if the flow of the pipeline to release the lock, the write thread to get the outer layer of the public lock. Here is a demo, for reference only, there may be problems:
Static Boolean end = False, @Testpublic void Test3 () throws IOException, interruptedexception {PipedInputStream pis = new PipedInputStream (); PipedOutputStream pos = new PipedOutputStream (pis); object monitor = new Object (); Countdownlatch latch = new Countdownlatch (2); new Thread (New Runnable () {@Overridepublic void run () {int count = 3;while (CO unt-->0) {synchronized (monitor) {System.out.println (count); byte[] B = new Byte[1022];try {pos.write (b, 0, b.length); Thread.Sleep (a);p os.write (1);} catch (IOException e) {e.printstacktrace ();} catch (Interruptedexception e) {e.printstacktrace ();} Monitor.notifyall (); try {monitor.wait (n);} catch (Interruptedexception e) {e.printstacktrace ();}}} End = true;try {Pos.close ();} catch (IOException e) {e.printstacktrace ();} Latch.countdown ();}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buf = new byte[1024]; int len = 0; try {System.out.println ("reading"); Synchronized (monitor) {while (!end) {len = Pis.read (BUF); System.out.println ("Reading ..."); Baos.write (buf, 0, Len); Monitor.notifyall (); try {monitor.wait (+);} catch (Interruptedexception e) {e.printstacktrace ();} }}} catch (IOException e) {e.printstacktrace ();} Byte[] result = Baos.tobytearray (); System.out.println (Result.length + ":" + arrays.tostring (result)); Latch.countdown ();}}). Start (); Latch.await ();}
Again, this code is not carefully thought out, just provide a way of thinking, the problem is not responsible for the use of pipeline flow best or one-time write all the data better.
Java IO (eight) Pipediutputstream and PipedOutputStream