Java NIO源码分析
1.前言
JDK1.4之前的传统阻塞IO(BIO),服务端需要为每一个客户端连接创建单独的线程为其服务,从JDK1.4开始NIO非阻塞式IO出现,它只需要单独的一个线程就能接收多个客户端请求,而真正处理各个请求的细节可以使用多线程的方式高效率的完成,这些处理线程与具体的业务逻辑分离,做到了IO的复用。
2.源码分析
首先以一段典型的NIO使用代码开始:
1 Selector selector = Selector.open(); 2 ServerSocketChannel ssc = ServerSocketChannel.open(); 3 ssc.configureBlocking(false); 4 ssc.socket().bind(new InetSocketAddress(9527)); 5 ssc.register(selector, SelectionKey.OP_ACCEPT); 6 while(true){ 7 int n = selector.select(); 8 if (n <= 0) continue; 9 Iterator it = selector.selectedKeys().iterator(); 10 while(it.hasNext()){ 11 SelectionKey key = (SelectionKey)it.next(); 12 if (key.isAcceptable()){ 13 SocketChannel sc= ((ServerSocketChannel) key.channel()).accept(); 14 sc.configureBlocking(false); 15 sc.register(key.selector(), SelectionKey.OP_READ|SelectionKey.OP_WRITE); 16 } 17 if (key.isReadable()){ 18 SocketChannel channel = ((SocketChannel) key.channel()); 19 ByteBuffer bf = ByteBuffer.allocate(10); 20 int read = channel.read(bf); 21 System.out.println("read "+read+" : "+new String(bf.array()).trim()); 22 } 23 if (key.isWritable()){ 24 SocketChannel channel = ((SocketChannel) key.channel()); 25 channel.write(ByteBuffer.wrap(new String("hello client").getBytes())); 26 } 27 it.remove(); 28 } 29 }
2.1 Selector.open() 获取选择器。
1 public static Selector open() throws IOException { 2 return SelectorProvider.provider().openSelector(); 3 } 4 public static SelectorProvider provider() { 5 synchronized (lock) { 6 if (provider != null) 7 return provider; 8 return AccessController.doPrivileged( 9 new PrivilegedAction<SelectorProvider>() { 10 public SelectorProvider run() { 11 if (loadProviderFromProperty()) 12 return provider; 13 if (loadProviderAsService()) 14 return provider; 15 provider = sun.nio.ch.DefaultSelectorProvider.create(); 16 return provider; 17 } 18 }); 19 } 20 }
从Selector源码中可以看到,open方法是交给selectorProvider处理的。 其中provider = sun.nio.ch.DefaultSelectorProvider.create();会根据操作系统来返回不同的实现类,windows平台就返回WindowsSelectorProvider;Linux平台会根据不同的内核版本选择是使用select/poll模式还是epoll模式。
Linux下defaultselectorprovider代码
1 public static SelectorProvider create() { 2 PrivilegedAction pa = new GetPropertyAction("os.name"); 3 String osname = (String) AccessController.doPrivileged(pa); 4 if ("SunOS".equals(osname)) { 5 return new sun.nio.ch.DevPollSelectorProvider(); 6 } 7 8 // use EPollSelectorProvider for Linux kernels >= 2.6 9 if ("Linux".equals(osname)) { 10 pa = new GetPropertyAction("os.version"); 11 String osversion = (String) AccessController.doPrivileged(pa); 12 String[] vers = osversion.split("\\.", 0); 13 if (vers.length >= 2) { 14 try { 15 int major = Integer.parseInt(vers[0]); 16 int minor = Integer.parseInt(vers[1]); 17 if (major > 2 || (major == 2 && minor >= 6)) { 18 return new sun.nio.ch.EPollSelectorProvider(); 19 } 20 } catch (NumberFormatException x) { 21 // format not recognized 22 } 23 } 24 } 25 return new sun.nio.ch.PollSelectorProvider(); 26 } 27 28 sun.nio.ch.EPollSelectorProvider 29 public AbstractSelector openSelector() throws IOException { 30 return new EPollSelectorImpl(this); 31 } 32 sun.nio.ch.PollSelectorProvider 33 public AbstractSelector openSelector() throws IOException { 34 return new PollSelectorImpl(this); 35 }
可以看到,如果Linux内核版本>=2.6则,具体的SelectorProvider为EPollSelectorProvider,否则为默认的PollSelectorProvider,实际上这是在JDK5U9之后才有这样的更新。
Windows下代码:
1 public static SelectorProvider create() { 2 return new sun.nio.ch.WindowsSelectorProvider(); 3 } 4 5 sun.nio.ch.WindowsSelectorProvider 6 public AbstractSelector openSelector() throws IOException { 7 return new WindowsSelectorImpl(this); 8 } 9 10 WindowsSelectorImpl(SelectorProvider sp) throws IOException { 11 super(sp); 12 pollWrapper = new PollArrayWrapper(INIT_CAP); 13 wakeupPipe = Pipe.open(); 14 wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal(); 15 16 // Disable the Nagle algorithm so that the wakeup is more immediate 17 SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink(); 18 (sink.sc).socket().setTcpNoDelay(true); 19 wakeupSinkFd = ((SelChImpl)sink).getFDVal(); 20 21 pollWrapper.addWakeupSocket(wakeupSourceFd, 0); 22 } 23 void addWakeupSocket(int fdVal, int index) { 24 putDescriptor(index, fdVal); 25 putEventOps(index, POLLIN); 26 }
接下来,以Windows的实现为准进行分析。在openSelector方法里面实例化WindowsSelectorImpl的过程中,
1).实例化了PollWrapper,pollWrapper用Unsafe类申请一块物理内存,用于存放注册时的socket句柄fdVal和event的数据结构pollfd.
2)Pipe.open()打开一个管道(打开管道的实现后面再看);拿到wakeupSourceFd和wakeupSinkFd两个文件描述符;把唤醒端的文件描述符(wakeupSourceFd)放到pollWrapper里.addWakeupSocket方法将source的POLLIN事件(有数据可读)标识为感兴趣的,当sink端有数据写入时,source对应的文件描述描wakeupSourceFd就会处于就绪状态.
Pipe.open():
1 public static Pipe open() throws IOException { 2 return SelectorProvider.provider().openPipe(); 3 } 4 5 public Pipe openPipe() throws IOException { 6 return new PipeImpl(this); 7 } 8 9 PipeImpl(final SelectorProvider sp) throws IOException { 10 try { 11 AccessController.doPrivileged(new Initializer(sp)); 12 } catch (PrivilegedActionException x) { 13 throw (IOException)x.getCause(); 14 } 15 } 16 private Initializer(SelectorProvider sp) { 17 this.sp = sp; 18 } 19 public Void run() throws IOException { 20 LoopbackConnector connector = new LoopbackConnector(); 21 connector.run(); 22 ....//省略 23 } 24 private class LoopbackConnector implements Runnable { 25 26 @Override 27 public void run() { 28 ServerSocketChannel ssc = null; 29 SocketChannel sc1 = null; 30 SocketChannel sc2 = null; 31 32 try { 33 // Loopback address 34 InetAddress lb = InetAddress.getByName("127.0.0.1"); 35 assert(lb.isLoopbackAddress()); 36 InetSocketAddress sa = null; 37 for(;;) { 38 // Bind ServerSocketChannel to a port on the loopback 39 // address 40 if (ssc == null || !ssc.isOpen()) { 41 ssc = ServerSocketChannel.open(); 42 ssc.socket().bind(new InetSocketAddress(lb, 0)); 43 sa = new InetSocketAddress(lb, ssc.socket().getLocalPort()); 44 } 45 46 // Establish connection (assume connections are eagerly 47 // accepted) 48 sc1 = SocketChannel.open(sa); 49 ByteBuffer bb = ByteBuffer.allocate(8); 50 long secret = rnd.nextLong(); 51 bb.putLong(secret).flip(); 52 sc1.write(bb); 53 54 // Get a connection and verify it is legitimate 55 sc2 = ssc.accept(); 56 bb.clear(); 57 sc2.read(bb); 58 bb.rewind(); 59 if (bb.getLong() == secret) 60 break; 61 sc2.close(); 62 sc1.close(); 63 } 64 65 // Create source and sink channels 66 source = new SourceChannelImpl(sp, sc1); 67 sink = new SinkChannelImpl(sp, sc2); 68 } catch (IOException e) { 69 try { 70 if (sc1 != null) 71 sc1.close(); 72 if (sc2 != null) 73 sc2.close(); 74 } catch (IOException e2) {} 75 ioe = e; 76 } finally { 77 try { 78 if (ssc != null) 79 ssc.close(); 80 } catch (IOException e2) {} 81 } 82 } 83 } 84 }
通过创建管道的代码分析:创建管道的具体实现方式也是与具体的操作系统紧密相关的,这里以Windows为例,创建了一个PipeImpl对象, AccessController.doPrivileged调用后紧接着会执行initializer的run方法,在run方法里面,windows下的实现是创建两个本地的socketChannel,然后连接(链接的过程通过写一个随机long做两个socket的链接校验),两个socketChannel分别实现了管道的source与sink端。通过查阅资料,而在Linux下则是直接使用操作系统提供的管道。
到这里,Selector.open()就完成了,总结一下,主要完成以下几件事:
1.实例化pollWrapper对象,用于将来存放注册时的socket句柄fdVal和event的数据结构pollfd。
2.根据不同操作系统实现了用于自我唤醒的管道,Windows通过创建一对自己连着自己的socket通道,Linux直接使用系统提供的管道。同时,根据linux的不同内核版本还会选择底层进行事件通知的不同机制select/poll或者epoll。
2.2 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);通道注册
1 public final SelectionKey register(Selector sel, int ops, Object att) 2 throws ClosedChannelException{ 3 synchronized (regLock) { 4 SelectionKey k = findKey(sel); 5 if (k != null) { 6 k.interestOps(ops); 7 k.attach(att); 8 } 9 if (k == null) { 10 // New registration 11 synchronized (keyLock) { 12 if (!isOpen()) 13 throw new ClosedChannelException(); 14 k = ((AbstractSelector)sel).register(this, ops, att); 15 addKey(k); 16 } 17 } 18 return k; 19 } 20 }
如果该channel和selector已经注册过,则直接添加事件和附件。否则通过selector实现注册过程。
1 protected final SelectionKey register(AbstractSelectableChannel ch, 2 int ops, Object attachment) { 3 if (!(ch instanceof SelChImpl)) 4 throw new IllegalSelectorException(); 5 SelectionKeyImpl k = new SelectionKeyImpl((SelChImpl)ch, this); 6 k.attach(attachment); 7 synchronized (publicKeys) { 8 implRegister(k); 9 } 10 k.interestOps(ops); 11 return k; 12 } 13 14 protected void implRegister(SelectionKeyImpl ski) { 15 synchronized (closeLock) { 16 if (pollWrapper == null) 17 throw new ClosedSelectorException(); 18 growIfNeeded(); 19 channelArray[totalChannels] = ski; 20 ski.setIndex(totalChannels); 21 fdMap.put(ski); 22 keys.add(ski); 23 pollWrapper.addEntry(totalChannels, ski); 24 totalChannels++; 25 } 26 } 27 28 private void growIfNeeded() { 29 if (channelArray.length == totalChannels) { 30 int newSize = totalChannels * 2; // Make a larger array 31 SelectionKeyImpl temp[] = new SelectionKeyImpl[newSize]; 32 System.arraycopy(channelArray, 1, temp, 1, totalChannels - 1); 33 channelArray = temp; 34 pollWrapper.grow(newSize); 35 } 36 if (totalChannels % MAX_SELECTABLE_FDS == 0) { // more threads needed 37 pollWrapper.addWakeupSocket(wakeupSourceFd, totalChannels); 38 totalChannels++; 39 threadsCount++; 40 } 41 } 42 void addEntry(int index, SelectionKeyImpl ski) { 43 putDescriptor(index, ski.channel.getFDVal()); 44 }
通过selector注册的过程主要完成以下几件事:
- 以当前channel和selector为参数,初始化 SelectionKeyImpl 对象,并添加附件attachment。
- 如果当前channel的数量totalChannels等于SelectionKeyImpl数组大小,对SelectionKeyImpl数组和pollWrapper进行扩容操作。
- 如果totalChannels % MAX_SELECTABLE_FDS == 0,则多开一个线程处理selector。windows上select系统调用有最大文件描述符限制,一次只能轮询1024个文件描述符,如果多于1024个,需要多线程进行轮询。
- ski.setIndex(totalChannels)选择键记录下在数组中的索引位置。
- keys.add(ski);将选择键加入到已注册键的集合中。
- fdMap.put(ski);保存选择键对应的文件描述符与选择键的映射关系。
- pollWrapper.addEntry将把selectionKeyImpl中的socket句柄添加到对应的pollfd。
- k.interestOps(ops)方法最终也会把event添加到对应的pollfd。
2.3 selector.select();
1 public int select() throws IOException { 2 return select(0); 3 } 4 public int select(long timeout) throws IOException 5 { 6 if (timeout < 0) 7 throw new IllegalArgumentException("Negative timeout"); 8 return lockAndDoSelect((timeout == 0) ? -1 : timeout); 9 } 10 private int lockAndDoSelect(long timeout) throws IOException { 11 synchronized (this) { 12 if (!isOpen()) 13 throw new ClosedSelectorException(); 14 synchronized (publicKeys) { 15 synchronized (publicSelectedKeys) { 16 return doSelect(timeout); 17 } 18 } 19 } 20 }
当调用selector.select()以及select(0)时,JDK对参数进行修正,其实传给doSelect的timeout为-1。当调用的是selectNow()的时候,timeout则为0,直接以负数作为参数则会抛出异常,其中的doSelector又回到我们的Windows实现:
1 protected int doSelect(long timeout) throws IOException { 2 if (channelArray == null) 3 throw new ClosedSelectorException(); 4 this.timeout = timeout; // set selector timeout 5 processDeregisterQueue(); 6 if (interruptTriggered) { 7 resetWakeupSocket(); 8 return 0; 9 } 10 // Calculate number of helper threads needed for poll. If necessary 11 // threads are created here and start waiting on startLock 12 adjustThreadsCount(); 13 finishLock.reset(); // reset finishLock 14 // Wakeup helper threads, waiting on startLock, so they start polling. 15 // Redundant threads will exit here after wakeup. 16 startLock.startThreads(); 17 // do polling in the main thread. Main thread is responsible for 18 // first MAX_SELECTABLE_FDS entries in pollArray. 19 try { 20 begin(); 21 try { 22 subSelector.poll(); 23 } catch (IOException e) { 24 finishLock.setException(e); // Save this exception 25 } 26 // Main thread is out of poll(). Wakeup others and wait for them 27 if (threads.size() > 0) 28 finishLock.waitForHelperThreads(); 29 } finally { 30 end(); 31 } 32 // Done with poll(). Set wakeupSocket to nonsignaled for the next run. 33 finishLock.checkForException(); 34 processDeregisterQueue(); 35 int updated = updateSelectedKeys(); 36 // Done with poll(). Set wakeupSocket to nonsignaled for the next run. 37 resetWakeupSocket(); 38 return updated; 39 } 40 private int poll() throws IOException{ // poll for the main thread 41 return poll0(pollWrapper.pollArrayAddress, 42 Math.min(totalChannels, MAX_SELECTABLE_FDS), 43 readFds, writeFds, exceptFds, timeout); 44 }
processDeregisterQueue方法主要是对已取消的键集合进行处理,通过调用cancel()方法将选择键加入已取消的键集合中,该方法将会从channelArray中移除对应的通道,调整通道数和线程数,从map和keys中移除选择键,移除通道上的选择键并关闭通道。同时还发现该方法在调用poll方法前后都进行调用,这是确保能够正确处理在调用poll方法阻塞的这一段时间之内取消的键能被及时清理。
adjustThreadsCount方法类似与前面的线程数调整,针对操作系统的最大select操作的文件描述符限制对线程个数进行调整。
subSelector.poll() 是select的核心,由native函数poll0实现,并把pollWrapper.pollArrayAddress作为参数传给poll0,readFds、writeFds 和exceptFds数组用来保存底层select的结果,数组的第一个位置都是存放发生事件的socket的总数,其余位置存放发生事件的socket句柄fd。
1 WindowsSelectorImpl.c 2 ---- 3 Java_sun_nio_ch_WindowsSelectorImpl_00024SubSelector_poll0(JNIEnv *env, jobject this, 4 jlong pollAddress, jint numfds, 5 jintArray returnReadFds, jintArray returnWriteFds, 6 jintArray returnExceptFds, jlong timeout) 7 { 8 static struct timeval zerotime = {0, 0}; 9 if (timeout == 0) { 10 tv = &zerotime; 11 } else if (timeout < 0) { 12 tv = NULL; 13 } else { 14 tv = &timevalue; 15 tv->tv_sec = (long)(timeout / 1000); 16 tv->tv_usec = (long)((timeout % 1000) * 1000); 17 } 18 // 代码.... 此处省略 19 20 /* Call select */ 21 if ((result = select(0 , &readfds, &writefds, &exceptfds, tv)) 22 == SOCKET_ERROR) { 23 /* Bad error - this should not happen frequently */ 24 /* Iterate over sockets and call select() on each separately */ 25 // 代码.... 此处省略 26 27 for (i = 0; i < numfds; i++) { 28 /* prepare select structures for the i-th socket */ 29 // 代码.... 此处省略 30 31 /* call select on the i-th socket */ 32 if (select(0, &errreadfds, &errwritefds, &errexceptfds, &zerotime) 33 == SOCKET_ERROR) { 34 //代码....此处省略 35 } 36 } 37 } 38 }
通过这一段调用C语言的poll0实现(这段代码主要意义在于调用了select函数,其他逻辑只是针对发生SOCKET_ERROR错误的时候,对每一个socket进行了单独的select调用),我们可以看到,Windows调用了底层的select函数,这里的select就是轮询pollArray中的FD,看有没有事件发生,如果有事件发生收集所有发生事件的FD,退出阻塞。当调用selector.select()以及select(0)时,JDK对参数进行修正,其实传给底层poll0的timeout为-1。当调用的是selectNow()的时候,timeout则为0,直接以负数作为参数则会抛出异常,当传给底层select的参数tv为0时立即返回,为NULL时将会无限期阻塞直到事件发生。
最后一步调用updateSelectedKeys。这个方法完成了选择键的更新,具体实现:
1 private int updateSelectedKeys() { 2 updateCount++; 3 int numKeysUpdated = 0; 4 numKeysUpdated += subSelector.processSelectedKeys(updateCount); 5 for (SelectThread t: threads) { 6 numKeysUpdated += t.subSelector.processSelectedKeys(updateCount); 7 } 8 return numKeysUpdated; 9 } 10 //以上对主线程和各个helper线程(因为最大文件句柄数限制作出线程调整创建的线程)都调用了 11 processSelectedKeys方法。 12 private int processSelectedKeys(long updateCount) { 13 int numKeysUpdated = 0; 14 numKeysUpdated += processFDSet(updateCount, readFds, 15 PollArrayWrapper.POLLIN, 16 false); 17 numKeysUpdated += processFDSet(updateCount, writeFds, 18 PollArrayWrapper.POLLCONN | 19 PollArrayWrapper.POLLOUT, 20 false); 21 numKeysUpdated += processFDSet(updateCount, exceptFds, 22 PollArrayWrapper.POLLIN | 23 PollArrayWrapper.POLLCONN | 24 PollArrayWrapper.POLLOUT, 25 true); 26 return numKeysUpdated; 27 } 28 //processSelectedKeys方法分别对读选择键集、写选择键集,异常选择键集调用了processFDSet方法 29 private int processFDSet(long updateCount, int[] fds, int rOps, 30 boolean isExceptFds) 31 { 32 int numKeysUpdated = 0; 33 for (int i = 1; i <= fds[0]; i++) { 34 int desc = fds[i]; 35 if (desc == wakeupSourceFd) { 36 synchronized (interruptLock) { 37 interruptTriggered = true; 38 } 39 continue; 40 } 41 MapEntry me = fdMap.get(desc); 42 // If me is null, the key was deregistered in the previous 43 // processDeregisterQueue. 44 if (me == null) 45 continue; 46 SelectionKeyImpl sk = me.ski; 47 48 // The descriptor may be in the exceptfds set because there is 49 // OOB data queued to the socket. If there is OOB data then it 50 // is discarded and the key is not added to the selected set. 51 if (isExceptFds && 52 (sk.channel() instanceof SocketChannelImpl) && 53 discardUrgentData(desc)) 54 { 55 continue; 56 } 57 58 if (selectedKeys.contains(sk)) { // Key in selected set 59 if (me.clearedCount != updateCount) { 60 if (sk.channel.translateAndSetReadyOps(rOps, sk) && 61 (me.updateCount != updateCount)) { 62 me.updateCount = updateCount; 63 numKeysUpdated++; 64 } 65 } else { // The readyOps have been set; now add 66 if (sk.channel.translateAndUpdateReadyOps(rOps, sk) && 67 (me.updateCount != updateCount)) { 68 me.updateCount = updateCount; 69 numKeysUpdated++; 70 } 71 } 72 me.clearedCount = updateCount; 73 } else { // Key is not in selected set yet 74 if (me.clearedCount != updateCount) { 75 sk.channel.translateAndSetReadyOps(rOps, sk); 76 if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) { 77 selectedKeys.add(sk); 78 me.updateCount = updateCount; 79 numKeysUpdated++; 80 } 81 } else { // The readyOps have been set; now add 82 sk.channel.translateAndUpdateReadyOps(rOps, sk); 83 if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) { 84 selectedKeys.add(sk); 85 me.updateCount = updateCount; 86 numKeysUpdated++; 87 } 88 } 89 me.clearedCount = updateCount; 90 } 91 } 92 return numKeysUpdated; 93 }
通过以上代码分析:
1、忽略wakeupSourceFd,这个文件描述符用于唤醒用的,与用户具体操作无关,所以忽略;
2、过滤fdMap中不存在的文件描述符,因为已被注销;
3、忽略oob data(搜了一下:out of band data指带外数据,有时也称为加速数据, 是指连接双方中的一方发生重要事情,想要迅速地通知对方 ),这也不是用户关心的;
4、如果通道的键还没有处于已选择的键的集合中,那么键的ready集合将被清空,然后表示操作系统发现的当前通道已经准备好的操作的比特掩码将被设置;
5、如果键在已选择的键的集合中。操作系统发现的当前已经准备好的操作的比特掩码将会被更新进ready集合,而对已经存在的任何结果集不做清除处理。
2.4 wakeup
1 public Selector wakeup() { 2 synchronized (interruptLock) { 3 if (!interruptTriggered) { 4 setWakeupSocket(); 5 interruptTriggered = true; 6 } 7 } 8 return this; 9 } 10 11 // Sets Windows wakeup socket to a signaled state. 12 private void setWakeupSocket() { 13 setWakeupSocket0(wakeupSinkFd); 14 } 15 16 private native void setWakeupSocket0(int wakeupSinkFd); 17 18 19 //WindowsSelectorImpl.c 20 JNIEXPORT void JNICALL 21 Java_sun_nio_ch_WindowsSelectorImpl_setWakeupSocket0(JNIEnv *env, jclass this, 22 jint scoutFd) 23 { 24 /* Write one byte into the pipe */ 25 send(scoutFd, (char*)&POLLIN, 1, 0); 26 }
如果线程正阻塞在select方法上,调用wakeup方法会使阻塞的选择操作立即返回,通过以上Windows的实现其实是向pipe的sink端写入了一个字节,source文件描述符就会处于就绪状态,poll方法会返回,从而导致select方法返回。而在其他solaris或者linux系统上其实采用系统调用pipe来完成管道的创建,相当于直接用了系统的管道。通过以上代码还可以看出,调用wakeup设置了interruptTriggered的标志位,所以连续多次调用wakeup的效果等同于一次调用。

浙公网安备 33010602011771号