jdk源碼解析八之Piped管道流

demo

package io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * Java IO中的管道爲運行在同一個JVM中的兩個線程提供了通信的能力。所以管道也可以作爲數據源以及目標媒介
 *
 * DataInputStream 讀取的數據由大於一個字節的Java原語(如int,long,float,double等)組成
 * SequenceInputStream 將兩個或者多個輸入流當成一個輸入流依次讀取
 */
public class PipeExample {
    public static void main(String[] args) throws IOException {
        final PipedOutputStream pipedOutputStream = new PipedOutputStream();
        final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
        //pipedInputStream.connect(pipedOutputStream); 也可以連接
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    pipedOutputStream.write("hello".getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    pipedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread = new Thread(new Runnable() {
            public void run() {
                try {
                    int read;
                    while ((read = pipedInputStream.read()) != -1) {
                        System.out.println((char) read);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    pipedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        thread1.start();


    }
}

PipedInputStream


public class PipedInputStream extends InputStream {
    //分別標記當前讀管道,寫管道的狀態
    boolean closedByWriter = false;
    volatile boolean closedByReader = false;
    //標記是否連接到寫管道
    boolean connected = false;


        //讀寫2個線程
    Thread readSide;
    Thread writeSide;

    //默認管道緩衝區大小
    private static final int DEFAULT_PIPE_SIZE = 1024;

    protected static final int PIPE_SIZE = DEFAULT_PIPE_SIZE;

    protected byte buffer[];

 
    //下一個寫入字節位置   in=out則說明滿了
    protected int in = -1;


    //下一個讀取字節位置
    protected int out = 0;

 
    public PipedInputStream(PipedOutputStream src) throws IOException {
        this(src, DEFAULT_PIPE_SIZE);
    }

  
    public PipedInputStream(PipedOutputStream src, int pipeSize)
            throws IOException {
        //初始化緩衝區大小,默認大小1024
         initPipe(pipeSize);
         //將當前對象傳入PipedOutputStream
         connect(src);
    }


    public PipedInputStream() {
        //初始化緩衝區大小,默認大小1024
        initPipe(DEFAULT_PIPE_SIZE);
    }


    public PipedInputStream(int pipeSize) {
        //初始化指定大小的緩衝區
        initPipe(pipeSize);
    }

    private void initPipe(int pipeSize) {
        //初始化指定大小管道緩衝區
         if (pipeSize <= 0) {
            throw new IllegalArgumentException("Pipe Size <= 0");
         }
         buffer = new byte[pipeSize];
    }


    public void connect(PipedOutputStream src) throws IOException {
        //管道連接
        src.connect(this);
    }


    //接受output發送過來的數據
    protected synchronized void receive(int b) throws IOException {
        checkStateForReceive();
        //獲取當前線程
        writeSide = Thread.currentThread();
        //讀滿,則等待,通知其他讀線程,我要開始寫了
        if (in == out)
            awaitSpace();
        //讀滿或初次讀取,則重置下標
        if (in < 0) {
            in = 0;
            out = 0;
        }
        //寫入數據
        buffer[in++] = (byte)(b & 0xFF);
        //超過邊界則從0開始
        if (in >= buffer.length) {
            in = 0;
        }
    }


    synchronized void receive(byte b[], int off, int len)  throws IOException {
        //檢查讀寫管道狀態是否正常開放
        checkStateForReceive();
        writeSide = Thread.currentThread();
        int bytesToTransfer = len;
        while (bytesToTransfer > 0) {
            //讀滿,則等待,通知其他讀線程,我要開始寫了
            if (in == out)
                awaitSpace();

            int nextTransferAmount = 0;

            //如果還有空間可以讀取,則獲取最大可讀取大小
            if (out < in) {
                nextTransferAmount = buffer.length - in;
            } else if (in < out) {
                //讀滿或者初次讀取則重置
                if (in == -1) {
                    in = out = 0;
                    nextTransferAmount = buffer.length - in;
                } else {
                //讀到這裏說明in走了一圈,重置爲0了
                    nextTransferAmount = out - in;
                }
            }
            //讀取空間足夠
            if (nextTransferAmount > bytesToTransfer)
                nextTransferAmount = bytesToTransfer;
            assert(nextTransferAmount > 0);
            //寫入範圍數據到buffer
            System.arraycopy(b, off, buffer, in, nextTransferAmount);
            //記錄剩下還需要寫入的空間
            bytesToTransfer -= nextTransferAmount;
            off += nextTransferAmount;
            in += nextTransferAmount;
            //寫入超限,重置
            if (in >= buffer.length) {
                in = 0;
            }
        }
    }

    private void checkStateForReceive() throws IOException {
        //當前是否連接
        if (!connected) {
            throw new IOException("Pipe not connected");
        } else if (closedByWriter || closedByReader) {
            //當前讀寫管道是否關閉了
            throw new IOException("Pipe closed");
        } else if (readSide != null && !readSide.isAlive()) {
            //當前線程死了
            throw new IOException("Read end dead");
        }
    }

    private void awaitSpace() throws IOException {
        while (in == out) {
            //檢查讀寫管道狀態是否正常開放
            checkStateForReceive();

            /* full: kick any waiting readers */
            //通知
            notifyAll();
            try {
                //等待
                wait(1000);
            } catch (InterruptedException ex) {
                throw new java.io.InterruptedIOException();
            }
        }
    }


    synchronized void receivedLast() {
        //標記寫管道流關閉
        closedByWriter = true;
        //通知所有等待的線程
        notifyAll();
    }

 
    public synchronized int read()  throws IOException {
        //校驗當前線程是否正常連接
        if (!connected) {
            throw new IOException("Pipe not connected");
        } else if (closedByReader) {
            //當前讀管道是否關閉
            throw new IOException("Pipe closed");
        } else if (writeSide != null && !writeSide.isAlive()
                   && !closedByWriter && (in < 0)) {
            //寫線程是否存活,以及是否關閉了寫流
            throw new IOException("Write end dead");
        }

        readSide = Thread.currentThread();
        int trials = 2;
        //等待寫入
        while (in < 0) {
            //寫入流關閉,則返回-1
            if (closedByWriter) {
                /* closed by writer, return EOF */
                return -1;
            }
            //寫線程已經不存活了,則拋異常
            if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {
                throw new IOException("Pipe broken");
            }
            /* might be a writer waiting */
            //通知線程,開始讀了
            notifyAll();
            try {
                //等待
                wait(1000);
            } catch (InterruptedException ex) {
                throw new java.io.InterruptedIOException();
            }
        }
        //讀入數據
        int ret = buffer[out++] & 0xFF;
        //讀到緩衝區上限則重置
        if (out >= buffer.length) {
            out = 0;
        }
        //讀滿則重置
        if (in == out) {
            /* now empty */
            in = -1;
        }

        return ret;
    }


    public synchronized int read(byte b[], int off, int len)  throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        /* possibly wait on the first character */
        //嘗試讀取一個字節
        int c = read();
        //沒數據則直接返回
        if (c < 0) {
            return -1;
        }
        b[off] = (byte) c;

        int rlen = 1;
        while ((in >= 0) && (len > 1)) {

            int available;

            //獲取可讀取的範圍
            if (in > out) {
                available = Math.min((buffer.length - out), (in - out));
            } else {
                //執行到這裏,說明in寫了一圈了.
                available = buffer.length - out;
            }

            // A byte is read beforehand outside the loop
            //可讀取的空間足夠,則直接讀取len-1長度
            if (available > (len - 1)) {
                available = len - 1;
            }
            System.arraycopy(buffer, out, b, off + rlen, available);
            out += available;
            rlen += available;
            len -= available;

            //讀到緩衝區上限則重置
            if (out >= buffer.length) {
                out = 0;
            }
            //讀滿則重置
            if (in == out) {
                /* now empty */
                in = -1;
            }
        }
        return rlen;
    }


    public synchronized int available() throws IOException {
        //讀滿,或者第一次讀取,則暫無字節可讀取
        if(in < 0)
            return 0;
        else if(in == out)
            //讀滿,則重置範圍
            return buffer.length;
        else if (in > out)
            //還在一圈範圍內
            return in - out;
        else
            //讀取一圈
            return in + buffer.length - out;
    }

    public void close()  throws IOException {
        //標記當前讀流關閉
        closedByReader = true;
        synchronized (this) {
            in = -1;
        }
    }
}

PipedOutputStream



public
class PipedOutputStream extends OutputStream {

   
    private PipedInputStream sink;


    public PipedOutputStream(PipedInputStream snk)  throws IOException {
        //管道連接
        connect(snk);
    }


    public PipedOutputStream() {
    }


    public synchronized void connect(PipedInputStream snk) throws IOException {
        if (snk == null) {
            throw new NullPointerException();
        } else if (sink != null || snk.connected) {
            throw new IOException("Already connected");
        }
        sink = snk;
        //標記初次寫入
        snk.in = -1;
        //讀取起始位置
        snk.out = 0;
        //標記狀態爲連接
        snk.connected = true;
    }

  
    public void write(int b)  throws IOException {
        if (sink == null) {
            throw new IOException("Pipe not connected");
        }
        //往input寫入數據
        sink.receive(b);
    }

  
    public void write(byte b[], int off, int len) throws IOException {
        if (sink == null) {
            throw new IOException("Pipe not connected");
        } else if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                   ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        //往input寫入指定範圍數據
        sink.receive(b, off, len);
    }


    //強制喚醒所有阻塞狀態
    public synchronized void flush() throws IOException {
        if (sink != null) {
            synchronized (sink) {
                //通知其他
                sink.notifyAll();
            }
        }
    }


    public void close()  throws IOException {
        //標記當前管道已經關閉
        if (sink != null) {
            sink.receivedLast();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章