The speed comes from using structures that are closer to the operating system's way of performing io:channels and buffers.
You could think of it as a coal mine;the channel is the mine containing the seam of the coal(the data), and the buffer is the cart that you send into the mine.
The cart comes back full of coal, and you get the coal from the cart. That is ,you don't interact directly with the channel; you interact with the buffer and send the buffer into the channel. The channel either pulls data from the buffer,or puts data into the buffer.
The only kind of buffer that communicates directly with a channel is a ByteBuffer——that is ,a buffer that holds raw bytes. If you look at the jdk doc for java.nio.ByteBuffer,you'll see that it is fairly basic:you create one by telling it how much storage to allocate,and there are methods to put and get data, in either raw byte form or as primitive data types. But there's no way to put or get an object, or even a string. it's fairly low-level, precisely because this makes a more efficient mapping with most operating systems;
传统IO不断的浪费对象资源(通常识string),nio通过使用缓冲区读写数据避免了资源浪费。缓冲区是一个数据容器,可以把它看成内存中一个大的数组,用来存储来自channel的同一类型的所有数据,因此,程序员可以使用字节,字符,整数等缓冲区。字节缓冲区提供必要的方法,可以提取或存入所有基本类型。
Buffer 是一个抽象类,他的基本属性包括capacity、limit、position、mark。
capacity: 这个buffer最多能房多少数据。一般在创建时指定
limit:在buffer上进行的读、写操作都不能超越这个下标。当写数据到buffer中时,limit一般和capacity相当;当读数据时,limit代表buffer中有效长度
position:读写操作的当前下标。当使用buffer的相对位置进行读写时,读写会从当前下标开始,并在完成后,更新position
mark:一个临时存放的位置下标。调用mark()会将mark设为当前的position值,以后调用reset()会将position属性设置为mark的值。mark的值总是小于等于position,若将position的值设置的小于mark,那么当前的mark将被舍弃。
这些属性满足 0 ≤ mark ≤ position ≤ limit ≤ capacity。对于初始化的buffer来说,position为0,limit = capacity
Executors
Executor 类是一种有效的、广泛使用的以工作队列为基础的线程池的正确实现。