攻破 JAVA NIO 技术壁垒( 下 ) 2017-09-02 ImportNew (点击上方公众号,可快速关注) 来源:朱小厮, blog.csdn.net/u013256816/articl

攻破 JAVA NIO 技术壁垒( 下 )

2017-09-02  ImportNew

(点击上方公众号,可快速关注)


来源:朱小厮,

blog.csdn.net/u013256816/article/details/51457215#comments

如有好文章投稿,请点击 → 这里了解详情


内存映射文件


JAVA处理大文件,一般用BufferedReader,BufferedInputStream这类带缓冲的IO类,不过如果文件超大的话,更快的方式是采用MappedByteBuffer。


MappedByteBuffer是NIO引入的文件内存映射方案,读写性能极高。NIO最主要的就是实现了对异步操作的支持。其中一种通过把一个套接字通道(SocketChannel)注册到一个选择器(Selector)中,不时调用后者的选择(select)方法就能返回满足的选择键(SelectionKey),键中包含了SOCKET事件信息。这就是select模型。


SocketChannel的读写是通过一个类叫ByteBuffer来操作的.这个类本身的设计是不错的,比直接操作byte[]方便多了. ByteBuffer有两种模式:直接/间接.间接模式最典型(也只有这么一种)的就是HeapByteBuffer,即操作堆内存 (byte[]).但是内存毕竟有限,如果我要发送一个1G的文件怎么办?不可能真的去分配1G的内存.这时就必须使用”直接”模式,即 MappedByteBuffer,文件映射.


先中断一下,谈谈操作系统的内存管理.一般操作系统的内存分两部分:物理内存;虚拟内存.虚拟内存一般使用的是页面映像文件,即硬盘中的某个(某些)特殊的文件.操作系统负责页面文件内容的读写,这个过程叫”页面中断/切换”. MappedByteBuffer也是类似的,你可以把整个文件(不管文件有多大)看成是一个ByteBuffer.MappedByteBuffer 只是一种特殊的ByteBuffer,即是ByteBuffer的子类。 MappedByteBuffer 将文件直接映射到内存(这里的内存指的是虚拟内存,并不是物理内存)。通常,可以映射整个文件,如果文件比较大的话可以分段进行映射,只要指定文件的那个部分就可以。


概念


FileChannel提供了map方法来把文件影射为内存映像文件: MappedByteBuffer map(int mode,long position,long size); 可以把文件的从position开始的size大小的区域映射为内存映像文件,mode指出了 可访问该内存映像文件的方式:


  • READ_ONLY,(只读): 试图修改得到的缓冲区将导致抛出 ReadOnlyBufferException.(MapMode.READ_ONLY)

  • READ_WRITE(读/写): 对得到的缓冲区的更改最终将传播到文件;该更改对映射到同一文件的其他程序不一定是可见的。 (MapMode.READ_WRITE)

  • PRIVATE(专用): 对得到的缓冲区的更改不会传播到文件,并且该更改对映射到同一文件的其他程序也不是可见的;相反,会创建缓冲区已修改部分的专用副本。 (MapMode.PRIVATE)


MappedByteBuffer是ByteBuffer的子类,其扩充了三个方法:


  • force():缓冲区是READ_WRITE模式下,此方法对缓冲区内容的修改强行写入文件;

  • load():将缓冲区的内容载入内存,并返回该缓冲区的引用;

  • isLoaded():如果缓冲区的内容在物理内存中,则返回真,否则返回假;


案例对比


这里通过采用ByteBuffer和MappedByteBuffer分别读取大小约为5M的文件”src/1.ppt”来比较两者之间的区别,method3()是采用MappedByteBuffer读取的,method4()对应的是ByteBuffer。


public static void method4(){

      RandomAccessFile aFile = null;

      FileChannel fc = null;

      try{

          aFile = new RandomAccessFile("src/1.ppt","rw");

          fc = aFile.getChannel();

 

          long timeBegin = System.currentTimeMillis();

          ByteBuffer buff = ByteBuffer.allocate((int) aFile.length());

          buff.clear();

          fc.read(buff);

          //System.out.println((char)buff.get((int)(aFile.length()/2-1)));

          //System.out.println((char)buff.get((int)(aFile.length()/2)));

          //System.out.println((char)buff.get((int)(aFile.length()/2)+1));

          long timeEnd = System.currentTimeMillis();

          System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");

 

      }catch(IOException e){

          e.printStackTrace();

      }finally{

          try{

              if(aFile!=null){

                  aFile.close();

              }

              if(fc!=null){

                  fc.close();

              }

          }catch(IOException e){

              e.printStackTrace();

          }

      }

  }

 

  public static void method3(){

      RandomAccessFile aFile = null;

      FileChannel fc = null;

      try{

          aFile = new RandomAccessFile("src/1.ppt","rw");

          fc = aFile.getChannel();

          long timeBegin = System.currentTimeMillis();

          MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, aFile.length());

          // System.out.println((char)mbb.get((int)(aFile.length()/2-1)));

          // System.out.println((char)mbb.get((int)(aFile.length()/2)));

          //System.out.println((char)mbb.get((int)(aFile.length()/2)+1));

          long timeEnd = System.currentTimeMillis();

          System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");

      }catch(IOException e){

          e.printStackTrace();

      }finally{

          try{

              if(aFile!=null){

                  aFile.close();

              }

              if(fc!=null){

                  fc.close();

              }

          }catch(IOException e){

              e.printStackTrace();

          }

      }

  }


通过在入口函数main()中运行:


method3();

       System.out.println("=============");

       method4();


输出结果(运行在普通PC机上):


Read time: 2ms

=============

Read time: 12ms


通过输出结果可以看出彼此的差别,一个例子也许是偶然,那么下面把5M大小的文件替换为200M的文件,输出结果:


Read time: 1ms

=============

Read time: 407ms


可以看到差距拉大。


注:MappedByteBuffer有资源释放的问题:被MappedByteBuffer打开的文件只有在垃圾收集时才会被关闭,而这个点是不确定的。在Javadoc中这里描述:A mapped byte buffer and the file mapping that it represents remian valid until the buffer itself is garbage-collected。详细可以翻阅参考资料5和6.


其余功能介绍


看完以上陈述,详细大家对NIO有了一定的了解,下面主要通过几个案例,来说明NIO的其余功能,下面代码量偏多,功能性讲述偏少。


Scatter/Gatter


分散(scatter)从Channel中读取是指在读操作时将读取的数据写入多个buffer中。因此,Channel将从Channel中读取的数据“分散(scatter)”到多个Buffer中。


聚集(gather)写入Channel是指在写操作时将多个buffer的数据写入同一个Channel,因此,Channel 将多个Buffer中的数据“聚集(gather)”后发送到Channel。


scatter / gather经常用于需要将传输的数据分开处理的场合,例如传输一个由消息头和消息体组成的消息,你可能会将消息体和消息头分散到不同的buffer中,这样你可以方便的处理消息头和消息体。


案例:


import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.nio.ByteBuffer;

import java.nio.channels.Channel;

import java.nio.channels.FileChannel;

 

public class ScattingAndGather

{

    public static void main(String args[]){

        gather();

    }

 

    public static void gather()

    {

        ByteBuffer header = ByteBuffer.allocate(10);

        ByteBuffer body = ByteBuffer.allocate(10);

 

        byte [] b1 = {'0', '1'};

        byte [] b2 = {'2', '3'};

        header.put(b1);

        body.put(b2);

 

        ByteBuffer [] buffs = {header, body};

 

        try

        {

            FileOutputStream os = new FileOutputStream("src/scattingAndGather.txt");

            FileChannel channel = os.getChannel();

            channel.write(buffs);

        }

        catch (IOException e)

        {

            e.printStackTrace();

        }

    }

}


transferFrom & transferTo


FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中。


public static void method1(){

        RandomAccessFile fromFile = null;

        RandomAccessFile toFile = null;

        try

        {

            fromFile = new RandomAccessFile("src/fromFile.xml","rw");

            FileChannel fromChannel = fromFile.getChannel();

            toFile = new RandomAccessFile("src/toFile.txt","rw");

            FileChannel toChannel = toFile.getChannel();

 

            long position = 0;

            long count = fromChannel.size();

            System.out.println(count);

            toChannel.transferFrom(fromChannel, position, count);

 

        }

        catch (IOException e)

        {

            e.printStackTrace();

        }

        finally{

            try{

                if(fromFile != null){

                    fromFile.close();

                }

                if(toFile != null){

                    toFile.close();

                }

            }

            catch(IOException e){

                e.printStackTrace();

            }

        }

    }


方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。


transferTo()方法将数据从FileChannel传输到其他的channel中。


public static void method2()

   {

       RandomAccessFile fromFile = null;

       RandomAccessFile toFile = null;

       try

       {

           fromFile = new RandomAccessFile("src/fromFile.txt","rw");

           FileChannel fromChannel = fromFile.getChannel();

           toFile = new RandomAccessFile("src/toFile.txt","rw");

           FileChannel toChannel = toFile.getChannel();

 

           long position = 0;

           long count = fromChannel.size();

           System.out.println(count);

           fromChannel.transferTo(position, count,toChannel);

 

       }

       catch (IOException e)

       {

           e.printStackTrace();

       }

       finally{

           try{

               if(fromFile != null){

                   fromFile.close();

               }

               if(toFile != null){

                   toFile.close();

               }

           }

           catch(IOException e){

               e.printStackTrace();

           }

       }

   }


上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。


Pipe


Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。


public static void method1(){

        Pipe pipe = null;

        ExecutorService exec = Executors.newFixedThreadPool(2);

        try{

            pipe = Pipe.open();

            final Pipe pipeTemp = pipe;

 

            exec.submit(new Callable<Object>(){

                @Override

                public Object call() throws Exception

                {

                    Pipe.SinkChannel sinkChannel = pipeTemp.sink();//向通道中写数据

                    while(true){

                        TimeUnit.SECONDS.sleep(1);

                        String newData = "Pipe Test At Time "+System.currentTimeMillis();

                        ByteBuffer buf = ByteBuffer.allocate(1024);

                        buf.clear();

                        buf.put(newData.getBytes());

                        buf.flip();

 

                        while(buf.hasRemaining()){

                            System.out.println(buf);

                            sinkChannel.write(buf);

                        }

                    }

                }

            });

 

            exec.submit(new Callable<Object>(){

                @Override

                public Object call() throws Exception

                {

                    Pipe.SourceChannel sourceChannel = pipeTemp.source();//向通道中读数据

                    while(true){

                        TimeUnit.SECONDS.sleep(1);

                        ByteBuffer buf = ByteBuffer.allocate(1024);

                        buf.clear();

                        int bytesRead = sourceChannel.read(buf);

                        System.out.println("bytesRead="+bytesRead);

                        while(bytesRead >0 ){

                            buf.flip();

                            byte b[] = new byte[bytesRead];

                            int i=0;

                            while(buf.hasRemaining()){

                                b[i]=buf.get();

                                System.out.printf("%X",b[i]);

                                i++;

                            }

                            String s = new String(b);

                            System.out.println("=================||"+s);

                            bytesRead = sourceChannel.read(buf);

                        }

                    }

                }

            });

        }catch(IOException e){

            e.printStackTrace();

        }finally{

            exec.shutdown();

        }

    }


DatagramChannel


Java NIO中的DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入。它发送和接收的是数据包。


public static void  reveive(){

       DatagramChannel channel = null;

       try{

           channel = DatagramChannel.open();

           channel.socket().bind(new InetSocketAddress(8888));

           ByteBuffer buf = ByteBuffer.allocate(1024);

           buf.clear();

           channel.receive(buf);

 

           buf.flip();

           while(buf.hasRemaining()){

               System.out.print((char)buf.get());

           }

           System.out.println();

 

       }catch(IOException e){

           e.printStackTrace();

       }finally{

           try{

               if(channel!=null){

                   channel.close();

               }

           }catch(IOException e){

               e.printStackTrace();

           }

       }

   }

 

   public static void send(){

       DatagramChannel channel = null;

       try{

           channel = DatagramChannel.open();

           String info = "I'm the Sender!";

           ByteBuffer buf = ByteBuffer.allocate(1024);

           buf.clear();

           buf.put(info.getBytes());

           buf.flip();

 

           int bytesSent = channel.send(buf, new InetSocketAddress("10.10.195.115",8888));

           System.out.println(bytesSent);

       }catch(IOException e){

           e.printStackTrace();

       }finally{

           try{

               if(channel!=null){

                   channel.close();

               }

           }catch(IOException e){

               e.printStackTrace();

           }

       }

   }


可以通过阅读参考资料2和3了解更多的NIO细节知识,前人栽树后人乘凉,这里就不赘述啦。


参考资料


  • Java NIO

    http://tutorials.jenkov.com/java-nio/nio-vs-io.html

  • Java NIO 系列教程

    http://ifeve.com/java-nio-all/

  • Java NIO 详解

    http://www.cnblogs.com/phoebus0501/archive/2010/12/05/1897245.html

  • 《深入分析Java Web技术内幕》许令波 著

  •  java大文件读写操作,java nio 之MappedByteBuffer,高效文件/内存映射

    http://langgufu.iteye.com/blog/2107023

  • java nio 之MappedByteBuffer,高效文件/内存映射

    http://www.360doc.com/content/13/0302/18/11314689_268892455.shtml#


看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

阅读原文
阅读  3009
16 投诉
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值