java-nio

NIO.

Java non-blocking IO (NIO)

  • Support form JDK 1.4
  • java.nio.buffer
    capacity
    limit
    position
    mark
  • Allocate buffer

    1
    2
    ByteBuffer buf = ByteBuffer.allocate(20); // allocate in heap.
    ByteBuffer buf = ByteBuffer.allocateDirect(20;) // allocate in off-heap.
  • ByteBuffer common operations

    • rewind() : pos=0, mark discard
    • clear() : pos=0, lim=cap, mark discard
    • flip() : lim=pos, pos=0, mark discard
    • reset() : pos=mark
    • slice() : split a buffer at remaining position

Garbage Collection (GC)

System.gc()

Channel

  1. FileChannel
    Copy file by Channel.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public void copyFile() {
    try {
    FileInputStream fis = new FileInputStream("TestChannelSrc.txt");
    FileChannel fcin = fis.getChannel();
    FileOutputStream fos = new FileOutputStream("TestChannelDst.txt");
    FileChannel fcout = fos.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024 * 50);
    while(fcin.read(buf) != -1) {
    buf.flip();
    fcout.write(buf);
    buf.clear();
    }
    fis.close();
    fos.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
  2. SocketChannel
    SocketChannelImage
    Full code can be found on github.

  3. MappedByteBuffer
    Map File on device to memory synchronizely.
    Full code can be found on github.