概述
JDK7引入了Asynchronous
I/O。I/O编程中,常用到两种模式:Reactor 和 Proactor。Reactor就是Java的NIO。当有事件触发时,我们得到通知,进行相应的处理。Proactor就是我们今天要讲的 AIO了。AIO进行I/O操作,都是异步处理,当事件完成时,我们会得到通知。
JDK7的 AIO包括网络和文件操作。两者大同小异,本文通过一个完整的客户端/服务器Sample来详细说明aio的网络操作。
AIO提供了两种异步操作的监听机制。第一种通过返回一个Future对象来事件,调用其get()会等到操作完成。第二种类似于回调函数。在进行异步操作时,传递一个CompletionHandler,当异步操作结束时,会调用CompletionHandler.complete
接口
范例
这个范例功能比较简单,就是客户端向服务端发送一个“test”命令,然后结束。
服务端程序
Sever.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Server {
private AsynchronousServerSocketChannel server;
public Server()throws IOException{
server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8888));
}
public void start() throws InterruptedException, ExecutionException, TimeoutException{
Future<AsynchronousSocketChannel> future = server.accept();
AsynchronousSocketChannel socket = future.get();
ByteBuffer readBuf = ByteBuffer.allocate(1024);
socket.read(readBuf).get(100, TimeUnit.SECONDS);
System.out.printf("Receiver:%s%n",new String(readBuf.array()));
}
public static void main(String args[]) throws Exception{
new Server().start();
}
}
客户端程序 (Future版本)
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
public class AIOClientWithFuture {
private final AsynchronousSocketChannel client;
public AIOClientWithFuture() throws IOException{
client = AsynchronousSocketChannel.open();
}
public void sendMsg() throws InterruptedException, ExecutionException{
client.connect(new InetSocketAddress("localhost",8888));
client.write(ByteBuffer.wrap("test".getBytes())).get();
}
public static void main(String...args) throws Exception{
AIOClientWithFuture client = new AIOClientWithFuture();
client.sendMsg();
}
}
客户端程序(CompleteHandler版本)
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AIOClientWithHandler {
private final AsynchronousSocketChannel client ;
public AIOClientWithHandler() throws Exception{
client = AsynchronousSocketChannel.open();
}
public void start()throws Exception{
client.connect(new InetSocketAddress("127.0.0.1",8888),null,new CompletionHandler<Void,Void>() {
@Override
public void completed(Void result, Void attachment) {
try {
client.write(ByteBuffer.wrap("test".getBytes())).get();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
}
public static void main(String args[])throws Exception{
new AIOClientWithHandler().start();
}
}
相关类说明
AsynchronousSocketChannel 跟 SocketChannel操作类似,只不过改成异步接口了
AsynchronousServerSocketChannel跟ServerSocketChannel操作类似,只不过改成异步接口了
CompletionHandler 接口包括两个方法
void completed(V result, A attachment);
void failed(Throwable exc, A attachment);
总结
本文只是对jdk7的aio使用做了一个简单的说明。至于其性能提升多少,如何改进现有的网络应用程序,还在摸索中。这里推荐一个比较成熟的网络框架Project Grizzly:http://grizzly.dev.java.net。据说已经用aio重新实现了,有兴趣的同学可以去研究一下源码。
参考资料
(以下有些资料使用的jdk7版本太低,很多接口已经更改了,慎入!:)
http://www.ibm.com/developerworks/java/library/j-nio2-1/index.html?
http://www.iteye.com/topic/446298
http://www.iteye.com/topic/472333
本文是jdk7系列的终结了,感谢大家的支持!更多的内容可以访问我的blog
http://www.iamcoding.com
分享到:
相关推荐
1.1 JDK7新特性<一>概述 . . . . . . . . . ....1.2 JDK7新特性<二> 语法 ....1.3 JDK7新特性<三> JDBC4.1 ....1.4 JDK7新特性<四> NIO2.0 文件系统 ....1.5 JDK7新特性<五> fork/...1.8 JDK7新特性<八>异步io/AIO . . . . . . . .
<groupId>javax.activation</groupId> <artifactId>javax.activation-api</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</...
新增: 利用itext7将html转pdf, 添加依赖: <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</... <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
<version>2.1.7.js7</version> <scope>compile</scope> <optional>false</optional> <exclusions> <exclusion> <groupId>org.bouncycastle</groupId> <artifactId>bcmail-jdk15on</artifactId> </exclusion> ...
<artifactId>jdk.tools</artifactId> <version>1.8</version> <scope>system</scope> <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath> </dependency> <dependency> <groupId>junit</groupId> ...
<classifier>jdk15</classifier> </dependency> <dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>xom</groupId> ...
<font size="3"><font color="#ff0000">考试内容 <br /></font><strong>一、Java语言的特点和实现机制</strong><br /><br /><strong>二、Java体系结构</strong><br /><br />1.JDK目录结构。<br />2.Java的API结构...
<br/><br/>考试细则:<br/><br/>考试名称:<br/> The Sun Certified Java Programmer for JDK 1.1<br/> <br/>考试号:<br/> 310-022(IBM考生除外),310-023(只对IBM考生)<br/> <br/>推荐教材:<br/> SL-275 "Java ...
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature> ...
<td width="7"></td> <td width="605"></td> <td width="7"> </td> <td width="36" rowspan="9" valign="top"><img src="image/z1.jpg" width="36" height="1006"></td> </tr> <tr> <td height="108" ...
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature> ...
<id>tomcat7</id> <username>admin</username> <password>admin</password> </server> 3.配置jdk环境(注意是jdk,不能是jre)下载java jdk,并安装java jdk。下载地址:...
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> 或者直接下载这个包
<groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> ...
<value>55533</value> </commport> <!-- 通讯端口1024~65535之间未被使用的端口 --> <maxconn> <value>5</value> </maxconn> <!-- 可按照不同的柜台号配置不同的公钥 --> <merpos> <!-- 商户柜台号 --> ...
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-21.11-jdk17.jar</systemPath> </dependency> 2.刷新依赖后,复制提供的java示例代码,修改代码中你要转换的Word的文件的路径,然后直接...
<br/><br/>JavaServer Pages API Documentation<br/><br/>Servlet API Documentation <br/><br/>TLDDoc Generated Documentation<br/><br/>JSTL JavaDoc<br/><br/>并打包制作为方便查阅的CHM文档,内容涵盖JSP ...
白天由于网络问题 导致上传失败 现重新打包上传 <br/><br/><br/>*************************************************<br/>完美CHM文档,方法索引、搜索、书签、树形Contents一应俱全<br/><br/>根据Sun 公司完整发布...
SpringBoot2核心技术 SpringBoot2入门 环境要求 Java8及以上 Maven 3.3及以上: : maven设置 < mirrors> < mirror> < id>nexus-aliyun</ id> < mirrorOf>central</ mirrorOf> ... < id>jdk-1.8</ id>
<br>http://images.amazon.cn/7/71111790130914730-fm.jpg<br><br>【原 书 名】 Core Java 2, Volume II--Advanced Features (7th Edition) <br>【原出版社】 Prentice Hall PTR <br>【作 者】(美)Cay S.Horstmann...