Through a program, we can see a feature of sync: If memory buffering is implemented through an application (for example, through a bufferedoutputstream object, these buffers must be refreshed before the data is affected by sync and transferred to filedescriptor (for example, by calling outputstream. flush)(Removed from the 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); // The result is 63306299.
If I remove FD. Sync (), the value will be much smaller. I tested 118053 ....
So obviously, sync returns the result only when all data is flushed, which takes a long time...
Next I will post some source code about filedescriptor:
FD. incrementandgetusecount (); this is a line of code seen in the public fileinputstream (filedescriptor fdobj) function. The following is the source code of this function:
Private atomicinteger usecount;
Int incrementandgetusecount (){
Return usecount. incrementandget ();
}
Int decrementandgetusecount (){
Return usecount. decrementandget ();
}
The following is the close source code of fileinputstream:
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 ();
}
}
For the moment, we believe that one of the functions of file descriptors is to count. Many of the source code are native methods, so many Source Code cannot be seen, which is a tragedy .... For example, what is the close0 () method? It can be decided to be disabled, but what is it, and what resources are closed .. Don't understand. If you have any idea, please leave a message ..
Through testing, the file descriptor of a file stream can be used to assign the file descriptor to another file stream. However, if you assign the file descriptor of a file input stream to a file output stream, it will cause an IO exception (I tested it ).