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