java FileDescriptor 的sync

來源:互聯網
上載者:User

通過一個程式我們就可以看出sync的一個特點:如果正通過應用程式(例如,通過一個 BufferedOutputStream 對象)實現記憶體緩衝,那麼必須在資料受 sync 影響之前將這些緩衝區重新整理,並轉到 FileDescriptor 中(例如,通過調用 OutputStream.flush)(從api中摘下來的)。

FileOutputStream fo=new FileOutputStream("2.txt");
BufferedOutputStream out=new BufferedOutputStream(fo);
FileDescriptor fd=fo.getFD();
byte[] b="abc".getBytes();
out.write(b);

long start=System.nanoTime();
out.flush();
fd.sync();
long end=System.nanoTime();
System.out.println(end-start);                    //結果為63306299

如果我去掉fd.sync(),那麼這個值就會小的多了,我測試的是118053  。。。。

所以很明顯,這個函數的效果,sync是在flush掉所有的資料才返回,這將會佔用很長的一段時間。。。

接下來我貼一下關於FileDescriptor的一些源碼:

 fd.incrementAndGetUseCount();這是在public FileInputStream(FileDescriptor fdObj)函數中看到的一行代碼,接下來是這個函數的源碼:

 private AtomicInteger useCount;

int incrementAndGetUseCount() {
        return useCount.incrementAndGet();
    }

    int decrementAndGetUseCount() { 
        return useCount.decrementAndGet();
    }

以下是FileInputStream的close源碼:

public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
            /*
             * Decrement the FD use count associated with the channel
             * The use count is incremented whenever a new channel
             * is obtained from this stream.
             */
           fd.decrementAndGetUseCount();
           channel.close();
        }

        /*
         * Decrement the FD use count associated with this stream
         */
        int useCount = fd.decrementAndGetUseCount();

        /*
         * If FileDescriptor is still in use by another stream, the finalizer
         * will not close it.
         */
        if ((useCount <= 0) || !isRunningFinalize()) {
            close0();
        }
    }

我們暫且認為檔案描述符的一個作用是用來計數的。源碼中很多是native方法,所以很多源碼也看不到,悲劇。。。。比如close0()這個方法,是幹嘛的,可定是關閉的作用,但是這是關閉什麼的呢,關閉什麼資源的呢。。不懂,如果有大神知道的話,請留言。。

通過測試,一個檔案流的檔案描述符可以被用來賦給另外一個檔案流的檔案描述符。但是如果把一個檔案輸入資料流的檔案描述符賦給一個檔案輸出資料流,那麼會引發io異常(我測試過)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.