PipedInputStream and PipedOutputStream in java | Implement producer consumer and avoid deadlock

PipedInputStream and PipedOutputStream allows two running threads to communicate.
PipedInputStream and PipedOutputStream can be used for setting up producer and consumer pattern, where PipedInputStream will produce and PipedOutputStream will consume.



Program to show PipedInputStream and PipedOutputStream allows two running threads to communicate. And how  PipedInputStream and PipedOutputStream can be used for setting up producer and consumer pattern >

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/** JavaMadeSoEasy.com */
public class PipedStream {
   public static void main(String[] args) throws IOException, InterruptedException {
          //define PipedInputStream
          final PipedInputStream pis = new PipedInputStream();
          //define PipedOutputStream,connect PipedInputStream and PipedOutputStream
          final PipedOutputStream pos = new PipedOutputStream(pis);
          //Or, you may use connect method to connect PipedInputStream and PipedOutputStream
          //pos.connect(pis);
          // Create producerThread which produces
          Thread producerThread = new Thread() {
                 public void run() {
                       for (int i = 0; i < 5; i++) {
                              try {
                                     pos.write(i);
                                     System.out.println("write/produce : "+ i);
                                     Thread.sleep(100);
                              } catch (Exception e) {
                              }
                       }
                 }
          };
         
          // Create consumerThread which consumes
          Thread consumerThread = new Thread() {
                 public void run() {
                       try {
                              for (int i = 0; i < 5; i++)
                                     System.out.println("read/consume : "+pis.read());
                       } catch (Exception e) {
                       }
                 }
          };
          producerThread.start();
         
          //This minor delay will ensure that producerThread thread starts before consumerThread thread.
          Thread.sleep(100);     
         
          consumerThread.start();
   }
}
/*
write/produce : 0
read/consume : 0
write/produce : 1
write/produce : 2
write/produce : 3
write/produce : 4
read/consume : 1
read/consume : 2
read/consume : 3
read/consume : 4
*/


When PipedInputStream and PipedOutputStream can form deadlock?
Javadocs says typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.

No comments:

Post a Comment