JDK7 新特性 + Java虚拟机规范(Java_SE_7)

看附件

 

1. jdk7

1.1 JDK7新特性<一>概述 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3

1.2 JDK7新特性<二> .法 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

1.3 JDK7新特性<三> JDBC4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

1.4 JDK7新特性<四> NIO2.0 文件系. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15

1.5 JDK7新特性<五> fork/join 框架 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

1.6 JDK7新特性<六> .听文件系.的更改 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23

1.7 JDK7新特性<七> 遍.文件. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26

1.8 JDK7新特性<八>..io/AIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

第 2 / 34 .

http://janeky.iteye.net1.1 JDK7新特性<一>概述

1.1 JDK7新特性<一>概述
.表..: 2011-05-18

JDK7至今仍未正式.布。从官方的 milestone schedule(里程碑)可知,目前已.准.就.,.于..准..段,感.趣

的可以从官方下.JDK7....版。.者根据官方的相.文档,整理了.个系列的文章。

准.

JDK7下. http://download.java.net/jdk7/
API文档 http://download.java.net/jdk7/docs/api/


新特性

1.虚.机
支持...言
.格的.文件..


2..言
.法方面的更新 (.参考http://janeky.iteye.com/blog/1047799)
core .加.器(class-loader)的架..行了升.改.

第 3 / 34 .

http://janeky.iteye.net1.1 JDK7新特性<一>概述

提供..URLClassLoader的方法
并.框架和容器的更新 (.参考http://janeky.iteye.com/blog/1047805)


3.网.
提供更多的new I/O API(.参考 http://janeky.iteye.com/blog/1047804)
filesystem支持zip/jar.档
SCTP(Stream Control Transmission Protocol)
SDP(Socket Direct Protocol)
使用Windows Vista 的IPv6 stack
TLS 1.2


4.安全相.
Elliptic-curve cryptography (ECC)

5.国.化
Unicode6.0Local 增.
区. user local 和 user-interface local

6.
jdbc
第 4 / 34 .

http://janeky.iteye.net1.1 JDK7新特性<一>概述

JDBC4.1 (.参考http://janeky.iteye.com/blog/1047800)

7.
client
Java 2D 提供 XRender pipeline
. 6u10 .形特性提供新的平台apiSwing 支持光圈效果 (Nimbus look-and-feel)
Swing JLayer .件

8.
web
更新 XML stack

9.
mgmt
增. JMX Agent 和 MBeans

(注:.篇文章.表.,JDK7未正式公布,可能有.差,具体以官方正式版.准)

参考.料

Jdk7官网 http://openjdk.java.net/projects/jdk7/

第 5 / 34 .

http://janeky.iteye.net1.1 JDK7新特性<一>概述

更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 6 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

1.2 JDK7新特性<二> .法
.表..: 2011-05-18

JDK7.Java.法有少量更新,重点是在易用性和便捷性的改.。

1.二.制字面量
JDK7.始,.于可以用二.制来表示整数(byte,short,int和long)。使用二.制字面量的好.是,可以是
代.更容易被理解。.法非常..,只要在二.制数.前面加 0b或者0B

byte nByte = (byte)0b0001;
short nShort = (short)0B0010;
int nInt = 0b0011;
long nLong = 0b0100L;
2.数字字面量可以出.下..
.于一些比.大的数字,我.定.起来.是不方面,.常缺少或者增加位数。JDK7.我.提供了一.解决
方案,下..可以出.在数字字面量。

int a = 10_0000_0000;
long b = 0xffff_ffff_ffff_ffffl;
byte c = 0b0001_1000;
注意:.只能将下..置于数字之.,以下使用方法是..的,

1.数字的..或者.尾
第 7 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

2.小数点的前后
3.‘F’或者‘f’的后.
4.只能用数字的位置
int err1 = _11,err2=11_;
float err3=3._4,err4=3_.4;
long err5=0x888_f;
3.switch.句可以用字符串了
.个功能千呼万.,.于出来了

private static void switchString(String str){
switch(str){
case "one":
System.err.println("1");
break;
case "two":
System.out.println("2");
break;
default :
System.out.println("err");
}
}
4.泛型.例的.建可以通..型推断来.化
以后..建一个泛型.例,不需要再...明.型,只需用<>,..器会自...匹配

//例如
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
第 8 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

//可以.化.
Map<String, List<String>> myMap = new HashMap<>();
5.在可.参数方法中..非具体化参数(Non-Reifiable Formal Parameters),改...警告和..
有些参数.型,例如ArrayList<Number>和 List<String>,是非具体化的(non-reifiable).在...段,
..器会擦除..型信息。

Heap pollution指一个.量被指向.外一个不是相同.型的.量。例如

List l = new ArrayList<Number>();
List<String> ls = l; // unchecked warning
l.add(0, new Integer(42)); // another unchecked warning
String s = ls.get(0); // ClassCastException is thrown
回到我.的主.,在jdk7中,当.定.下面的函数.

public static <T> void addToList (List<T> listArg, T... elements) {
for (T x : elements) {
listArg.add(x);
}
}
.会得到一个warning

warning: [varargs] Possible heap pollution from parameterized vararg type
在jdk7之前,当..用一个含有非具体化参数的可.参数方法,.必.自行保.不会.生“heap
pollution”。.有一个..,如果.用者.方法不熟悉,他根本无法判断。JDK7.此做了改.,在.方法被定
..久.出警告

第 9 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

要消除警告,可以有三.方式

1.加 annotation @SafeVarargs
2.加 annotation @SuppressWarnings({"unchecked", "varargs"})
3.使用..器参数 .Xlint:varargs;
6.try-with-resources .句
jdk7提供了try-with-resources,可以自...相.的.源(只要..源..了AutoCloseable接口,jdk7..
大部分.源.象都..了.个接口)

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
try .句.中.可以同..理多个.源,可以跟普通的try.句一.catch.常,有finally.句.

try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
}catch(…){
}finally{
}
7.Catch多个Exception,rethrow exception 改.了.型..
第 10 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

很多.候,我.捕.了多个.常,却做了相同的事情,比如.日志,包装成新的.常,然后rethrow。.
.,代.就不那..雅了,例如

catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}
Jdk7允.捕.多个.常

catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
注意,catch后面的.常参数是final的,不能重新再.制

Rethrow Exception更具包容性的.型..

当.重新抛出多个.常.,不再需要..定..常.型了,..器已.知道.具体抛出的是.个.常了。.
只需在方法定.的.候声明需要抛出的.常即可

第 11 / 34 .

http://janeky.iteye.net1.2 JDK7新特性<二> .法

public void call() throws ReflectiveOperationException, IOException {
try {
callWithReflection(arg);
} catch (final Exception e) {
logger.trace("Exception in reflection", e);
throw e;
}
}
参考.料

Jdk7官网
http://openjdk.java.net/projects/jdk7/

(注:.篇文章.表.,JDK7未正式公布,可能有.差,具体以官方正式版.准)

更多的jdk7文章,.迎..


http://janeky.iteye.com/category/157060

第 12 / 34 .

http://janeky.iteye.net1.3 JDK7新特性<三> JDBC4.1

1.3 JDK7新特性<三> JDBC4.1
.表..: 2011-05-18

JDBC4.1更新了.个新特性

1.Connection,ResultSet和 Statement都..了Closeable接口,所有在 try-with-resources.句中.
用,就可以自...相..源了
try (Statement stmt = con.createStatement()){

}
2. RowSet 1.1:引入RowSetFactory接口和RowSetProvider.,可以.建JDBC driver支持的各. row sets
RowSetFactory myRowSetFactory = null;
JdbcRowSet jdbcRs = null;
ResultSet rs = null;
Statement stmt = null;
try {
myRowSetFactory = RowSetProvider.newFactory();//用缺省的RowSetFactory ..
jdbcRs = myRowSetFactory.createJdbcRowSet();
//.建一个 JdbcRowSet .象,配置数据..接属性
jdbcRs.setUrl("jdbc:myDriver:myAttribute");
jdbcRs.setUsername(username);
jdbcRs.setPassword(password);
jdbcRs.setCommand("select ID from TEST");
第 13 / 34 .

http://janeky.iteye.net1.3 JDK7新特性<三> JDBC4.1

jdbcRs.execute();
}
RowSetFactory接口包括了.建不同.型的RowSet的方法

.createCachedRowSet
.createFilteredRowSet
.createJdbcRowSet
.createJoinRowSet
.createWebRowSet
参考.料

Jdk7官网 http://openjdk.java.net/projects/jdk7/

(注:.篇文章.表.,JDK7未正式公布,可能有.差,具体以官方正式版.准)

更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 14 / 34 .

http://janeky.iteye.net1.4 JDK7新特性<四> NIO2.0 文件系.

1.4 JDK7新特性<四> NIO2.0 文件系.
.表..: 2011-05-18

java.io.File 不.完美.。Jdk7提供了一套新的文件系.,会...意的。
先来聊聊java.io.File的七宗罪.:)

1.很多方法失..候都没有抛出.常,很..找原因
2.方法 rename 在不同平台中.行有..
3.不能真正支持 symbolic links
4.不能.取文件的更..属性,比如.限,所有者……
5... 文件的 metadata 效率低下
6.很多方法性能不行。例如.理比.大的目.
7.无法...找文件.,以及存在循.的symbolic links可能造成..
本次jdk7更新了很多新的api。方法太多了,我就不一一列.了,感.趣的可以去..api

http://download.java.net/jdk7/docs/api/java/nio/file/package-summary.html
主要包括:
FileSystem提供了.多方法来.得当前文件系.的相.信息。

第 15 / 34 .

http://janeky.iteye.net1.4 JDK7新特性<四> NIO2.0 文件系.

Path.理路径(文件和目.),包括
.建path,Paths.get(String s)
.得path的..信息 getName(),getXX()…
.除path的冗余信息 toRealPath
..path toAbsolutePath()
合并.个path resolve()
在.个path之..建相.路径 relativeze()
比.路径 equal() startsWith(),endWith()
Files支持各.文件操作,包括
移.文件,

.制文件,
.除文件,
更..的文件属性,包括文件.限,.建者,修改..……
Walkingthe File Tree(..遍.文件.)
Watch a Directory for Change (.听文件更改)


(最后.点,我近期会更新一些相.的范例)
更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 16 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

1.5 JDK7新特性<五> fork/join 框架
.表..: 2011-05-18

.于框架的原理,可以.. Doug Lea 的文章“A Java Fork/Join Framework”:了解 Fork/Join 模式的..
机制和.行性能。

原理解析:fork分解,join.合。.个框架的本.是将一个任.分解成多个子任.,.个子任.用.独的.程去
.理。.里用到了..的思想。框架的...可以参考


.片来源(http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/index.html)

使用fork/join框架很..,

1...子..的一般求解算法
2.如何分解..
3..承 RecursiveAction,..compute()方法
Result solve(Problem problem) {
if (problem is small)
第 17 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

directly solve problem
else {
split problem into independent parts
fork new subtasks to solve each part
join all subtasks
compose result from subresults
}
}
.里我通.一个改.的二分.找来.解fork/join的使用。(后面才..,.用.个案例是非常失.的,因.二
分.找的..是logn,而.建.程的..更大,..并不能体.多.程二分.找的..,所以.个代.不具有.
用性,只是.了.明如何使用框架:)

代.如下:

BinarySearchProblem.java

package testjdk7;
import java.util.Arrays;
/**
* @author kencs@foxmail.com
*/
public class BinarySearchProblem {
private final int[] numbers;
private final int start;
private final int end;
public final int size;
第 18 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

public BinarySearchProblem(int[] numbers,int start,int end){
this.numbers = numbers;
this.start = start;
this.end = end;
this.size = end -start;
}
public int searchSequentially(int numberToSearch){
//..,不自己写二分.找了
return Arrays.binarySearch(numbers, start, end, numberToSearch);
}
public BinarySearchProblem subProblem(int subStart,int subEnd){
return new BinarySearchProblem(numbers,start+subStart,start+subEnd);
}
}
BiSearchWithForkJoin.java

package testjdk7;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* @author kencs@foxmail.com
*/
public class BiSearchWithForkJoin extends RecursiveAction {
private final int threshold;
private final BinarySearchProblem problem;
public int result;
private final int numberToSearch;
public BiSearchWithForkJoin(BinarySearchProblem problem,int threshold,int numberToSearch){
第 19 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

this.problem = problem;
this.threshold = threshold;
this.numberToSearch = numberToSearch;
}
@Override
protected void compute() {
if(problem.size < threshold){ //小于..,就直接用普通的二分.找
result = problem.searchSequentially(numberToSearch);
}else{
//分解子任.
int midPoint = problem.size/2;
BiSearchWithForkJoin left = new BiSearchWithForkJoin(problem.subProblem(0, midPoint),threshold,BiSearchWithForkJoin right = new BiSearchWithForkJoin(problem.subProblem(midPoint+1, problem.invokeAll(left,right);
result = Math.max(left.result, right.result);
}
}
//.造数据
private static final int[] data = new int[1000_0000];
static{
for(int i = 0;i<1000_0000;i++){
data[i] = i;
}
}
public static void main(String[] args){
BinarySearchProblem problem = new BinarySearchProblem(data,0,data.length);
int threshold = 100;
int nThreads = 10;
//.找100_0000所在的下.
BiSearchWithForkJoin bswfj = new BiSearchWithForkJoin(problem,threshold,100_0000);
ForkJoinPool fjPool = new ForkJoinPool(nThreads);
fjPool.invoke(bswfj);
System.out.printf("Result is:%d%n",bswfj.result);
}
第 20 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

}
RecursiveTask.可以.返回.,.里.出一段代.作.参考(斐波那契函数)
(来自http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/index.html)

class Fibonacci extends RecursiveTask<Integer> {
final int n;
Fibonacci(int n) {
this.n = n;
}
private int compute(int small) {
final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
return results[small];
}
public Integer compute() {
if (n <= 10) {
return compute(n);
}
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
System.out.println("fork new thread for " + (n - 1));
f1.fork();
System.out.println("fork new thread for " + (n - 2));
f2.fork();
return f1.join() + f2.join();
}
}
第 21 / 34 .

http://janeky.iteye.net1.5 JDK7新特性<五> fork/join 框架

用途

只要..能.分解成.似子..的,都可以使用.个框架。.于大批量的数据尤其合.

参考.料
Jdk7官网
http://openjdk.java.net/projects/jdk7/


(注:.篇文章.表.,JDK7未正式公布,可能有.差,具体以官方正式版.准)

更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 22 / 34 .

http://janeky.iteye.net1.6 JDK7新特性<六> .听文件系.的更改

1.6 JDK7新特性<六> .听文件系.的更改
.表..: 2011-05-19

我.用IDE(例如Eclipse).程,外部更改了代.文件,IDE.上提升“文件有更改”。Jdk7的NIO2.0也提供
了.个功能,用于.听文件系.的更改。它采用.似.察者的模式,注册相.的文件更改事件(新建,.除
……),当事件.生的,通知相.的.听者。

java.nio.file.*包提供了一个文件更改通知API,叫做Watch Service API.

..流程如下

1..文件系..建一个WatchService .例 watcher
2...想.听的目.注册 watcher。注册.,要注明.听那些事件。
3.在无限循.里面等待事件的触.。当一个事件.生.,key.出信号,并且加入到watcher的queue
4.从watcher的queue.找到key,.可以从中.取到文件名等相.信息
5.遍.key的各.事件
6.重置 key,重新等待事件
7...服.
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
第 23 / 34 .

http://janeky.iteye.net1.6 JDK7新特性<六> .听文件系.的更改

import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;
/**
* @author kencs@foxmail.com
*/
public class TestWatcherService {
private WatchService watcher;
public TestWatcherService(Path path)throws IOException{
watcher = FileSystems.getDefault().newWatchService();
path.register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
}
public void handleEvents() throws InterruptedException{
while(true){
WatchKey key = watcher.take();
for(WatchEvent<?> event : key.pollEvents()){
WatchEvent.Kind kind = event.kind();
if(kind == OVERFLOW){//事件可能lost or discarded
continue;
}
WatchEvent<Path> e = (WatchEvent<Path>)event;
Path fileName = e.context();
System.out.printf("Event %s has happened,which fileName is %s%n"
,kind.name(),fileName);
}
if(!key.reset()){
break;
}
}
}
第 24 / 34 .

http://janeky.iteye.net1.6 JDK7新特性<六> .听文件系.的更改

public static void main(String args[]) throws IOException, InterruptedException{
if(args.length!=1){
System.out.println("..置要.听的文件目.作.参数");
System.exit(-1);
}
new TestWatcherService(Paths.get(args[0])).handleEvents();
}
}
接下来,..奇迹的.刻

1.随便新建一个文件.例如 c:\\test2..行程序 java TestWatcherService c:\\test3.在.文件.下新建一个文件本件“新建文本文档 .txt”
4.将上述文件改名. “abc.txt”
5.打.文件,.入点什..,再保存。
6.Over!看看命令行.出的信息.
Event ENTRY_CREATE has happened,which fileName is 新建文本文档.txtEvent ENTRY_DELETE has happened,which fileName is 新建文本文档.txt
Event ENTRY_CREATE has happened,which fileName is abc.txt
Event ENTRY_MODIFY has happened,which fileName is abc.txt
Event ENTRY_MODIFY has happened,which fileName is abc.txt
更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 25 / 34 .

http://janeky.iteye.net1.7 JDK7新特性<七> 遍.文件.

1.7 JDK7新特性<七> 遍.文件.
.表..: 2011-05-20

有.需要..遍.一个文件.,比如.找一个文件.内符合条件的文件,.找某一天.建的文件……。jdk7 nio
包提供一个新的接口 FileVisitor。它提供了遍.文件.的各.操作。

preVisitDirectory - 一个路径被....用

PostVisitDirectory - 一个路径的所有.点被..后.用。如果有...生,exception会....个方法

visitFile - 文件被...被.用。.文件的文件属性被....个方法

visitFileFailed - 当文件不能被...,此方法被.用。Exception被....个方法。

如果.比..,不想..所有方法。.可以...承 SimpleFileVisitor。它....了上述方法,.只需
Override .感.趣的方法。

下面.个例子,..地遍.一个文件.,打印出所有信息

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
第 26 / 34 .

http://janeky.iteye.net1.7 JDK7新特性<七> 遍.文件.

/**
* @author kencs@foxmail.com
*/
public class FileVisitorTest extends SimpleFileVisitor<Path> {
private void find(Path path){
System.out.printf("..-%s:%s%n",(Files.isDirectory(path)?"目.":"文件"),path.getFileName());
}
@Override
public FileVisitResult visitFile(Path file,BasicFileAttributes attrs){
find(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs){
find(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file,IOException e){
System.out.println(e);
return FileVisitResult.CONTINUE;
}
public static void main(String[] args) throws IOException{
if(args.length!=1){
System.out.println("..入一个文件路径作.参数");
System.exit(-1);
}
Files.walkFileTree(Paths.get( args[0]), new FileVisitorTest());
}
}
第 27 / 34 .

http://janeky.iteye.net1.7 JDK7新特性<七> 遍.文件.

随便..一个路径作.参数

java FileVisitorTest
"C:\\Program Files\\Java\\jre7\\bin"


..-目.:bin
..-文件:awt.dll
..-文件:axbridge.dll
..-目.:client
..-文件:classes.jsa
..-文件:jvm.dll
..-文件:Xusage.txt
..-文件:dcpr.dll
..-文件:deploy.dll
..-文件:deployJava1.dll
..-文件:dt_shmem.dll
..-文件:dt_socket.dll......
注意 FileVisitResult有四.

CONTINUE ...
TERMINATE ..止,.次遍..束了
SKIP_SUBTREE .子.(当前路径的子目.)不再遍.了
SKIP_SIBLINGS .兄弟.点(同..目.)不再..了。

可以通..些返回.来控制遍.文件.的流程

更多的jdk7文章,.迎..http://janeky.iteye.com/category/157060

第 28 / 34 .

http://janeky.iteye.net1.8 JDK7新特性<八>..io/AIO

1.8 JDK7新特性<八>..io/AIO
.表..: 2011-06-09

概述

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;
第 29 / 34 .

http://janeky.iteye.net1.8 JDK7新特性<八>..io/AIO

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();
第 30 / 34 .

http://janeky.iteye.net1.8 JDK7新特性<八>..io/AIO

}
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();
}
第 31 / 34 .

http://janeky.iteye.net1.8 JDK7新特性<八>..io/AIO

}
@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重新
..了,有.趣的同学可以去研究一下源.。

第 32 / 34 .

http://janeky.iteye.net1.8 JDK7新特性<八>..io/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

第 33 / 34 .

http://www.iteye.com- 做最棒的.件..交流社区

更多的技.文章 .迎..我的 blog <a
href="http://www.iamcoding.com">http://www.iamcoding.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值