对与Java NIO,以前没有接触过,最近学习Hadoop的Common包,看到IPC这部分,是由Java NIO实现的,所以赶紧学习以下Java NIO。
在Java中NIO使用起来比较方便,概念也比较清晰,主要参考了并发编程网的Java NIO教程:Java NIO 系列教程,通俗易懂,强烈推荐学习Java NIO的同学看这个教程。
先来看看阻塞与非阻塞,在这篇文章IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇),对于IO的这几个概念讲得比较清楚了,阻塞的的意思就是请求了另一个IO操作,然后进程(线程)就一直等待,直到IO操作返回结果,在等待的过程中什么也不做。非阻塞的意思是,在发起一个IO操作后就,进程可以做其他事情,IO操作返回后就再回来处理IO操作。除了阻塞与非阻塞,还需要理解IO multiplexing的概念,也就是在Socket编程中常说的select,epoll(epoll暂时没有接触过)的IO方式,select的IO方式就是同时监听多个IO操作,至少一个IO操作准备好时时就处理准备好的IO操作。异步IO的,感觉就与JavaScript中的Ajax异步传输类似,结合那篇讲IO操作的文章的作者在文章最后给出的例子很容易理解:
最后,再举几个不是很恰当的例子来说明这四个IO Model: 有A,B,C,D四个人在钓鱼: A用的是最老式的鱼竿,所以呢,得一直守着,等到鱼上钩了再拉杆; B的鱼竿有个功能,能够显示是否有鱼上钩,所以呢,B就和旁边的MM聊天,隔会再看看有没有鱼上钩,有的话就迅速拉杆; C用的鱼竿和B差不多,但他想了一个好办法,就是同时放好几根鱼竿,然后守在旁边,一旦有显示说鱼上钩了,它就将对应的鱼竿拉起来; D是个有钱人,干脆雇了一个人帮他钓鱼,一旦那个人把鱼钓上来了,就给D发个短信。
在传统的Java socket编程中,需要一个每一个socket连接对应一个线程来进行处理,在socket连接过程中如果没有消息发送,那么每一个线程都是阻塞的。整个过程是这样的,服务器端使用ServerSocket起一个socket连接,等待客户端的socket连接请求,当到达一个客户端的socket连接请求时,服务器端就用accept方法接收这个socket连接请求,然后创建一个线程来处理这个客户端的socket的IO。Java示例代码如下:
ServerSocket ss = new ServerSocket(8888); while(true) { Socket s = ss.accept(); ServerThread st = new ServerThread(s); }其中ServerThread是服务器端用于处理每一个连接到的socket的线程类。
Java NIO(New IO)是一个可以替代标准Java IO API的IO API(从Java 1.4开始),Java NIO提供了与标准IO不同的IO工作方式,是一种基于块的IO方式,主要用于处理Java中大并发的问题。NIO主要提供了Channel(管道),Buffer(缓冲块),Selectors(选择器)等概念。每一个IO连接对应一个Channel,IO传输的数据先存储在Buffer中,服务器端的ServerSocketChannel可以监听多个SocketChannel,使用Selectors来注册监听事件,每当有IO数据到达时,调用Selector的select()方法得到要取数据的Channel。借用并发编程网的一张图片,来展示一个单线程中使用一个Selector处理3个Channel:
对于Java NIO的的介绍,请参考Java NIO 系列教程
public class NIOSocketServer { public static final int PORT = 12306; public static final int BUFFER_SIZE = 1024; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); Selector selector = Selector.open(); serverSocketChannel.configureBlocking(false);//配置为非阻塞 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//用于接受连接 serverSocketChannel.socket().bind(new InetSocketAddress(PORT));//绑定端口 while(true) { int readyChannelNum = selector.select(); if(readyChannelNum > 0) { Set<SelectionKey> set = selector.selectedKeys();//用于获得当前可用的channel Iterator<SelectionKey> its = set.iterator();//遍历channel while(its.hasNext()) { SelectionKey selectionKey = its.next(); its.remove();//已经得到了,将channel移除 if(selectionKey.isAcceptable()) { SocketChannel channel = serverSocketChannel.accept(); channel.configureBlocking(false); System.out.println("a client connected"); SelectionKey connKey = channel.register(selector, SelectionKey.OP_READ); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); connKey.attach(buffer); } else if(selectionKey.isReadable()) { SocketChannel channel = (SocketChannel)selectionKey.channel(); ByteBuffer buffer = (ByteBuffer)selectionKey.attachment(); int bytesRead = channel.read(buffer); if(bytesRead == -1) { channel.close(); } else { buffer.flip(); while(buffer.hasRemaining()) { System.out.print((char)buffer.get()); } System.out.println(); selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } else if(selectionKey.isWritable()) { ByteBuffer sig = ByteBuffer.allocate(64); sig.put("received:".getBytes()); sig.flip(); ByteBuffer byteBuffer = (ByteBuffer)selectionKey.attachment(); SocketChannel channel = (SocketChannel)selectionKey.channel(); byteBuffer.flip(); while(byteBuffer.hasRemaining()) { channel.write(new ByteBuffer[]{sig, byteBuffer}); } byteBuffer.clear(); } } } } } }
public class NIOSocket { /** * @param args * @throws IOException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { InetSocketAddress server = new InetSocketAddress("127.0.0.1", 12306); SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(server); Selector selector = Selector.open(); channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); while(!channel.finishConnect()) { Thread.sleep(1000); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; ByteBuffer buffer = ByteBuffer.allocate(1024); boolean flag = true; while(flag) { int num = selector.select(); if(num == 0) { continue; } Set<SelectionKey> set = selector.selectedKeys(); Iterator<SelectionKey> keys = set.iterator(); while(keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if(key.isWritable()) { line = br.readLine(); if(line.equals("")) { flag = false; } buffer.put(line.getBytes()); buffer.flip(); SocketChannel writer = (SocketChannel)key.channel(); writer.write(buffer); buffer.clear(); key.interestOps(SelectionKey.OP_READ); } else if(key.isReadable()) { SocketChannel reader = (SocketChannel)key.channel(); int byteread = reader.read(buffer); if(byteread != -1) { buffer.flip(); while(buffer.hasRemaining()) { System.out.print((char)buffer.get()); } System.out.println(); buffer.clear(); } key.interestOps(SelectionKey.OP_WRITE); } } } } }