java FileDescriptor 的sync

通过一个程序我们就可以看出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异常(我测试过)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值