# what's NIO
It's intriduced in JDK 1.4, has one goal: speed! Rapidly moving large amounts of data.
Actually, the 'old IO' have been reimplemented using NIO.
# why NIO is fast?
The speed comes from using structure which is closer to the operating system's way of performing IO:
- Channel: like coal mine containing the seam of coal(data)
- Buffer: like the cart you send into the mine, the cart come back full of coal, we get coal from cart.
# FileChannel vs BufferInputStream/BufferOutputStream
after testing, I found that FileChannel is slower, super disappointed~~~
especially 'transferTo()' method is super slow '''
# view buffer
- which allows you to look at an underlying ByteBuffer through the window of a particular primitive type.
- ByteBuffer is still the actual storage that’s "backing" the view
- so any changes you make to the view are reflected in modifications to the data in the ByteBuffer.
ByteBuffer buffer = ByteBuffer.allocate(1024);
// intBuffer
IntBuffer intBuffer = buffer.asIntBuffer();
intBuffer.put(new int[] {0,1,2,3,4,5,6,7,8,9});
intBuffer.put(/*index*/ 0, /*value*/ 100);
# File locking
- File locking allows you to synchronize access to a file as a shared resource.
- two threads that contend for the same file may be in different JVMs, or one may be a Java thread and the other some native thread in the operating system
public class FileLocking {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("file.txt");
FileLock fLock = fos.getChannel().tryLock();
if (null != fLock) {
System.out.println("File locked");
TimeUnit.SECONDS.sleep(1);
fLock.release();
System.out.println("Release lock");
}
fos.close();
}
}