首页编程java编程java nio为什么比io快(Java中nio与普通io有什么优势)

java nio为什么比io快(Java中nio与普通io有什么优势)

编程之家2023-10-1392次浏览

大家好,如果您还对java nio为什么比io快不太了解,没有关系,今天就由本站为大家分享java nio为什么比io快的知识,包括Java中nio与普通io有什么优势的问题都会给大家分析到,还望可以解决大家的问题,下面我们就开始吧!

java nio为什么比io快(Java中nio与普通io有什么优势)

Java NIO与IO的区别和比较

J2SE1.4以上版本中发布了全新的I/O类库。本文将通过一些实例来简单介绍NIO库提供的一些新特性:非阻塞I/O,字符转换,缓冲以及通道。

一.介绍NIO

NIO包(java.nio.*)引入了四个关键的抽象数据类型,它们共同解决传统的I/O类中的一些问题。

java nio为什么比io快(Java中nio与普通io有什么优势)

1. Buffer:它是包含数据且用于读写的线形表结构。其中还提供了一个特殊类用于内存映射文件的I/O操作。

2. Charset:它提供Unicode字符串影射到字节序列以及逆影射的操作。

3. Channels:包含socket,file和pipe三种管道,它实际上是双向交流的通道。

java nio为什么比io快(Java中nio与普通io有什么优势)

4. Selector:它将多元异步I/O操作集中到一个或多个线程中(它可以被看成是Unix中select()函数或Win32中WaitForSingleEvent()函数的面向对象版本)。

二.回顾传统

在介绍NIO之前,有必要了解传统的I/O操作的方式。以网络应用为例,传统方式需要监听一个ServerSocket,接受请求的连接为其提供服务(服务通常包括了处理请求并发送响应)图一是服务器的生命周期图,其中标有粗黑线条的部分表明会发生I/O阻塞。

图一

可以分析创建服务器的每个具体步骤。首先创建ServerSocket

ServerSocket server=new ServerSocket(10000);

然后接受新的连接请求

Socket newConnection=server.accept();

对于accept方法的调用将造成阻塞,直到ServerSocket接受到一个连接请求为止。一旦连接请求被接受,服务器可以读客户socket中的请求。

InputStream in= newConnection.getInputStream();

InputStreamReader reader= new InputStreamReader(in);

BufferedReader buffer= new BufferedReader(reader);

Request request= new Request();

while(!request.isComplete()){

String line= buffer.readLine();

request.addLine(line);

}

这样的操作有两个问题,首先BufferedReader类的readLine()方法在其缓冲区未满时会造成线程阻塞,只有一定数据填满了缓冲区或者客户关闭了套接字,方法才会返回。其次,它回产生大量的垃圾,BufferedReader创建了缓冲区来从客户套接字读入数据,但是同样创建了一些字符串存储这些数据。虽然BufferedReader内部提供了StringBuffer处理这一问题,但是所有的String很快变成了垃圾需要回收。

同样的问题在发送响应代码中也存在

Response response= request.generateResponse();

OutputStream out= newConnection.getOutputStream();

InputStream in= response.getInputStream();

int ch;

while(-1!=(ch= in.read())){

out.write(ch);

}

newConnection.close();

类似的,读写操作被阻塞而且向流中一次写入一个字符会造成效率低下,所以应该使用缓冲区,但是一旦使用缓冲,流又会产生更多的垃圾。

传统的解决方法

通常在Java中处理阻塞I/O要用到线程(大量的线程)。一般是实现一个线程池用来处理请求,如图二

图二

线程使得服务器可以处理多个连接,但是它们也同样引发了许多问题。每个线程拥有自己的栈空间并且占用一些CPU时间,耗费很大,而且很多时间是浪费在阻塞的I/O操作上,没有有效的利用CPU。

三.新I/O

1. Buffer

传统的I/O不断的浪费对象资源(通常是String)。新I/O通过使用Buffer读写数据避免了资源浪费。Buffer对象是线性的,有序的数据集合,它根据其类别只包含唯一的数据类型。

java.nio.Buffer类描述

java.nio.ByteBuffer包含字节类型。可以从ReadableByteChannel中读在 WritableByteChannel中写

java.nio.MappedByteBuffer包含字节类型,直接在内存某一区域映射

java.nio.CharBuffer包含字符类型,不能写入通道

java.nio.DoubleBuffer包含double类型,不能写入通道

java.nio.FloatBuffer包含float类型

java.nio.IntBuffer包含int类型

java.nio.LongBuffer包含long类型

java.nio.ShortBuffer包含short类型

可以通过调用allocate(int capacity)方法或者allocateDirect(int capacity)方法分配一个Buffer。特别的,你可以创建MappedBytesBuffer通过调用FileChannel.map(int mode,long position,int size)。直接(direct)buffer在内存中分配一段连续的块并使用本地访问方法读写数据。非直接(nondirect)buffer通过使用Java中的数组访问代码读写数据。有时候必须使用非直接缓冲例如使用任何的wrap方法(如ByteBuffer.wrap(byte[]))在Java数组基础上创建buffer。

2.字符编码

向ByteBuffer中存放数据涉及到两个问题:字节的顺序和字符转换。ByteBuffer内部通过ByteOrder类处理了字节顺序问题,但是并没有处理字符转换。事实上,ByteBuffer没有提供方法读写String。

Java.nio.charset.Charset处理了字符转换问题。它通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。

3.通道(Channel)

你可能注意到现有的java.io类中没有一个能够读写Buffer类型,所以NIO中提供了Channel类来读写Buffer。通道可以认为是一种连接,可以是到特定设备,程序或者是网络的连接。通道的类等级结构图如下

图三

图中ReadableByteChannel和WritableByteChannel分别用于读写。

GatheringByteChannel可以从使用一次将多个Buffer中的数据写入通道,相反的,ScatteringByteChannel则可以一次将数据从通道读入多个Buffer中。你还可以设置通道使其为阻塞或非阻塞I/O操作服务。

为了使通道能够同传统I/O类相容,Channel类提供了静态方法创建Stream或Reader

4. Selector

在过去的阻塞I/O中,我们一般知道什么时候可以向stream中读或写,因为方法调用直到stream准备好时返回。但是使用非阻塞通道,我们需要一些方法来知道什么时候通道准备好了。在NIO包中,设计Selector就是为了这个目的。SelectableChannel可以注册特定的事件,而不是在事件发生时通知应用,通道跟踪事件。然后,当应用调用Selector上的任意一个selection方法时,它查看注册了的通道看是否有任何感兴趣的事件发生。图四是selector和两个已注册的通道的例子

图四

并不是所有的通道都支持所有的操作。SelectionKey类定义了所有可能的操作位,将要用两次。首先,当应用调用SelectableChannel.register(Selector sel,int op)方法注册通道时,它将所需操作作为第二个参数传递到方法中。然后,一旦SelectionKey被选中了,SelectionKey的readyOps()方法返回所有通道支持操作的数位的和。SelectableChannel的validOps方法返回每个通道允许的操作。注册通道不支持的操作将引发IllegalArgumentException异常。下表列出了SelectableChannel子类所支持的操作。

ServerSocketChannel OP_ACCEPT

SocketChannel OP_CONNECT, OP_READ, OP_WRITE

DatagramChannel OP_READ, OP_WRITE

Pipe.SourceChannel OP_READ

Pipe.SinkChannel OP_WRITE

四.举例说明

1.简单网页内容下载

这个例子非常简单,类SocketChannelReader使用SocketChannel来下载特定网页的HTML内容。

package examples.nio;

import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.net.InetSocketAddress;

import java.io.IOException;

public class SocketChannelReader{

private Charset charset=Charset.forName("UTF-8");//创建UTF-8字符集

private SocketChannel channel;

public void getHTMLContent(){

try{

connect();

sendRequest();

readResponse();

}catch(IOException e){

System.err.println(e.toString());

}finally{

if(channel!=null){

try{

channel.close();

}catch(IOException e){}

}

}

}

private void connect()throws IOException{//连接到CSDN

InetSocketAddress socketAddress=

new InetSocketAddress("http://www.csdn.net",80/);

channel=SocketChannel.open(socketAddress);

//使用工厂方法open创建一个channel并将它连接到指定地址上

//相当与SocketChannel.open().connect(socketAddress);调用

}

private void sendRequest()throws IOException{

channel.write(charset.encode("GET"

+"/document"

+"\r\n\r\n"));//发送GET请求到CSDN的文档中心

//使用channel.write方法,它需要CharByte类型的参数,使用

//Charset.encode(String)方法转换字符串。

}

private void readResponse()throws IOException{//读取应答

ByteBuffer buffer=ByteBuffer.allocate(1024);//创建1024字节的缓冲

while(channel.read(buffer)!=-1){

buffer.flip();//flip方法在读缓冲区字节操作之前调用。

System.out.println(charset.decode(buffer));

//使用Charset.decode方法将字节转换为字符串

buffer.clear();//清空缓冲

}

}

public static void main(String [] args){

new SocketChannelReader().getHTMLContent();

}

2.简单的加法服务器和客户机

服务器代码

package examples.nio;

import java.nio.ByteBuffer;

import java.nio.IntBuffer;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.net.InetSocketAddress;

import java.io.IOException;

/**

* SumServer.java

*

*

* Created: Thu Nov 06 11:41:52 2003

*

*@author starchu1981

*@version 1.0

*/

public class SumServer{

private ByteBuffer _buffer=ByteBuffer.allocate(8);

private IntBuffer _intBuffer=_buffer.asIntBuffer();

private SocketChannel _clientChannel=null;

private ServerSocketChannel _serverChannel=null;

public void start(){

try{

openChannel();

waitForConnection();

}catch(IOException e){

System.err.println(e.toString());

}

}

private void openChannel()throws IOException{

_serverChannel=ServerSocketChannel.open();

_serverChannel.socket().bind(new InetSocketAddress(10000));

System.out.println("服务器通道已经打开");

}

private void waitForConnection()throws IOException{

while(true){

_clientChannel=_serverChannel.accept();

if(_clientChannel!=null){

System.out.println("新的连接加入");

processRequest();

_clientChannel.close();

}

}

}

private void processRequest()throws IOException{

_buffer.clear();

_clientChannel.read(_buffer);

int result=_intBuffer.get(0)+_intBuffer.get(1);

_buffer.flip();

_buffer.clear();

_intBuffer.put(0,result);

_clientChannel.write(_buffer);

}

public static void main(String [] args){

new SumServer().start();

}

}// SumServer

客户代码

package examples.nio;

import java.nio.ByteBuffer;

import java.nio.IntBuffer;

import java.nio.channels.SocketChannel;

import java.net.InetSocketAddress;

import java.io.IOException;

/**

* SumClient.java

*

*

* Created: Thu Nov 06 11:26:06 2003

*

*@author starchu1981

*@version 1.0

*/

public class SumClient{

private ByteBuffer _buffer=ByteBuffer.allocate(8);

private IntBuffer _intBuffer;

private SocketChannel _channel;

public SumClient(){

_intBuffer=_buffer.asIntBuffer();

}// SumClient constructor

public int getSum(int first,int second){

int result=0;

try{

_channel=connect();

sendSumRequest(first,second);

result=receiveResponse();

}catch(IOException e){System.err.println(e.toString());

}finally{

if(_channel!=null){

try{

_channel.close();

}catch(IOException e){}

}

}

return result;

}

private SocketChannel connect()throws IOException{

InetSocketAddress socketAddress=

new InetSocketAddress("localhost",10000);

return SocketChannel.open(socketAddress);

}

private void sendSumRequest(int first,int second)throws IOException{

_buffer.clear();

_intBuffer.put(0,first);

_intBuffer.put(1,second);

_channel.write(_buffer);

System.out.println("发送加法请求"+first+"+"+second);

}

private int receiveResponse()throws IOException{

_buffer.clear();

_channel.read(_buffer);

return _intBuffer.get(0);

}

public static void main(String [] args){

SumClient sumClient=new SumClient();

System.out.println("加法结果为:"+sumClient.getSum(100,324));

}

}// SumClient

3.非阻塞的加法服务器

首先在openChannel方法中加入语句

_serverChannel.configureBlocking(false);//设置成为非阻塞模式

重写WaitForConnection方法的代码如下,使用非阻塞方式

private void waitForConnection()throws IOException{

Selector acceptSelector= SelectorProvider.provider().openSelector();

/*在服务器套接字上注册selector并设置为接受accept方法的通知。

这就告诉Selector,套接字想要在accept操作发生时被放在ready表

上,因此,允许多元非阻塞I/O发生。*/

SelectionKey acceptKey= ssc.register(acceptSelector,

SelectionKey.OP_ACCEPT);

int keysAdded= 0;

Java中nio与普通io有什么优势

1,nio的主要作用就是用来解决速度差异的。举个例子:计算机处理的速度,和用户按键盘的速度,这两者的速度相差悬殊。

2,如果按照经典的方法:一个用户设定一个线程,专门等待用户的输入,无形中就造成了严重的资源浪费,每一个线程都需要珍贵的cpu时间片,由于速度差异造成了在这个交互线程中的cpu都用来等待。

3,传统的阻塞式IO,每个连接必须要开一个线程来处理,并且没处理完线程不能退出。

4,非阻塞式IO,由于基于反应器模式,用于事件多路分离和分派的体系结构模式,所以可以利用线程池来处理。事件来了就处理,处理完了就把线程归还。

5,而传统阻塞方式不能使用线程池来处理,假设当前有10000个连接,非阻塞方式可能用1000个线程的线程池就搞定了,而传统阻塞方式就需要开10000个来处理。如果连接数较多将会出现资源不足的情况。非阻塞的核心优势就在这里。

io和nio的文件读取方式的不同

io,也称old io,读取文件主要通过流,从磁盘上一个一个字符的读,效率比较低下。

nio,在对文件操作下改进了方式,通过块读取,一整块一整块的读取,所以读取出来的不会是一个字符,而是一个块,把这些数据放到内存缓冲区内。在进行操作。通过块的读取来提高速度。(块操作,fileChannel)

内存映射,MappedByteBuffer,这个主要是通过内存映射,即利用虚拟内存(把文件某一部分当成内存),直接操作文件,对于一些要在内存中大块操作的文件,比如1G的文件

你要在内存中操作200M的部分,,把200M读到物理内存是比较耗内存和CPU的,不如直接把那部分文件虚拟成内存直接操作。

下面是对用以上三个文式对一个300M的文件进行读取,并写入另一个文件的测试:

1. inputstream CPU5.6%内存2.6M costTime:4.039S使用缓冲区byte:4kb

2. filechannel CPU1.3%内存2.6M costTime:3.359S使用缓冲区byte:0(transferTo方式)

3. MappedByteBuffer CPU6.9%内存2.4M costTime:6.966S内存映射:300M

可见对大文件块读取是最好的;如果要直接操作文件的很大的一部分的内容,则比较适合MappedByteBuffer;如读取很小的内容,比如8B的内容,inputStream可能是最好的。

代码如下,选几个文件自已试下。使用jdk自带JConsole进行观察。

public class Test{

public static void main(String[] args)throws Exception{

File ff=new File("F:/workspace/pureMQ/src/mq/pure/file/cc.rar");

File[] f=new File[7];

File[] f_write=new File[7];

Thread.sleep(15000);

for(int i=0;i<7;i++){

f[i]=new File("F:/workspace/pureMQ/src/mq/pure/file/1"+(i+1)+".jpg");

}

for(int i=0;i<7;i++){

f_write[i]=new File("F:/workspace/pureMQ/src/mq/pure/file/"+i+".jpg");

if(!f_write[i].exists()){

f_write[i].createNewFile();

}

}

f[0]=ff;

long begin=System.currentTimeMillis();

int choice=1;

for(int i=0;i<7;i++){

switch(choice){

case 1:

System.out.println("1");

InputStream ips=new FileInputStream(f[i]);

OutputStream ops=new FileOutputStream(f_write[i]);

byte[] b=new byte[4096];

int index;

while((index=ips.read(b))!=-1){

ops.write(b);

}

if(ips!=null){

ips.close();

}

if(ops!=null){

ops.close();

}

break;

case 2:

System.out.println("2");

RandomAccessFile raf=new RandomAccessFile(f[i],"r");

RandomAccessFile raf_write=new RandomAccessFile(f_write[i],"rw");

FileChannel fc=raf.getChannel();

FileChannel fc_write=raf_write.getChannel();

fc.transferTo(0, fc.size(), fc_write);

fc.close();

fc_write.close();

raf.close();

raf_write.close();

break;

case 3:

System.out.println("3");

RandomAccessFile raf2=new RandomAccessFile(f[i],"r");

RandomAccessFile raf2_write=new RandomAccessFile(f_write[i],"rwd");

FileChannel fc2=raf2.getChannel();

FileChannel fc2_write=raf2_write.getChannel();

MappedByteBuffer mbb=fc2_write.map(MapMode.READ_WRITE, 0, fc2.size());

ByteBuffer bb=ByteBuffer.allocate(4096);

while(fc2.read(bb)!=-1){

bb.flip();

mbb.put(bb);

bb.compact();

}

mbb.force();

fc2.close();

fc2_write.close();

raf2.close();

raf2_write.close();

break;

default:

break;

}

}

long end=System.currentTimeMillis();

System.out.println("all time cost:"+(end-begin));

}

}

关于本次java nio为什么比io快和Java中nio与普通io有什么优势的问题分享到这里就结束了,如果解决了您的问题,我们非常高兴。

java中什么叫初始化,java中的初始化具体是什么意思考哥 考哥配过哪些角色