Java7 I/O新功能探秘:同步操作,多播与随机存取

fmms 13年前
     <h3>Java7 I/O新功能探秘:同步操作,多播与随机存取</h3>    <div>     <ul>      <li>SeekableByteChannel:随机访问通道;</li>      <li>MulticastChannel:允许IP多播的通道;</li>      <li>NetworkChannel:新的网络通道超级接口;</li>      <li>异步I/O API:新的API使I/O操作可以异步进行。</li>     </ul>    </div>    <div>     <br />    </div>    <h2>SeekableByteChannel</h2>    <div>     首先,Java 7包括新的ByteChannel - SeekableByteChannel,这个通道维护当前的位置,你可以读写该位置,并允许随机访问。使用这个类型的通道,你可以添加多个线程读/写在不同位置相同的线程。     <pre class="brush:java; toolbar: true; auto-links: false;">SeekableByteChannel channel1 = Paths.get("Path to file").newByteChannel(); //Simply READ SeekableByteChannel channel2 = Paths.get("Path to file").newByteChannel(StandardOpenOption.READ, StandardOpenOption.WRITE); //READ and WRITE</pre>     <div>      你可以使用下面这些方法操作位置和通道的大小。     </div>     <div>      <ul>       <li>long position():返回目前的位置;</li>       <li>long size():返回通道连接实体的当前大小,如通道连接的文件大小;</li>       <li>position(long newPosition):移动当前位置到某个地方;</li>       <li>truncate(long size):根据给定大小截断实体。</li>      </ul>     </div>     <div>      position()和truncate()方法简单地返回当前通道,允许链式调用。现在FileChannel实现了新的接口,使用所有FileChannel你都可以实现随机访问,当然你可以用它读取一个文件:      <pre class="brush:java; toolbar: true; auto-links: false;">SeekableByteChannel channel = null; try {     channel = Paths.get("Path to file").newByteChannel(StandardOpenOption.READ);     ByteBuffer buffer = ByteBuffer.allocate(4096);       System.out.println("File size: " + channel.size());       while (channel.read(buffer) &gt; 0) {         buffer.rewind();           System.out.print(new String(buffer.array(), 0, buffer.remaining()));           buffer.flip();           System.out.println("Current position : " + channel.position());     } } catch (IOException e) {     System.out.println("Expection when reading : " + e.getMessage());     e.printStackTrace(); } finally {     if (sbc != null){         channel.close();     } }</pre>      <h2>MulticastChannel</h2>      <div>       这个新的接口允许开启IP多播,因此你可以向一个完整的组发送和接收IP数据报。多播实现了直接绑定本地多播设备,这个接口是通过 DatagramChannel和AsynchronousDatagramChannel实现的。下面是从Javadoc中摘取的一个打开 DatagramChannel t的简单示例:       <pre class="brush:java; toolbar: true; auto-links: false;">NetworkInterface networkInterface = NetworkInterface.getByName("hme0");   DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)          .setOption(StandardSocketOption.SO_REUSEADDR, true)          .bind(new InetSocketAddress(5000))          .setOption(StandardSocketOption.IP_MULTICAST_IF, networkInterface);   InetAddress group = InetAddress.getByName("225.4.5.6");   MembershipKey key = dc.join(group, networkInterface);</pre>       <div>        你可以使用以前经常使用的DatagramChannel,但操作方式是多播了,因此你收到的是接口中所有的数据包,你发送的数据包会发到所有组。       </div>       <div>        <br />       </div>       <h2>NetworkChannel</h2>       <div>        现在所有网络通道都实现了新的NetworkChannel接口,你可以轻松绑定套接字管道,设置和查询套接字选项,此外,套接字选项也被扩展了,因此你可以使用操作系统特定的选项,对于高性能服务器这非常有用。       </div>       <div>        <br />       </div>       <h2>异步I/O</h2>       <div>        现在我们介绍最重要的新特性:异步I/O API,从它的名字我们就知道它有什么功能了,这个新的通道为套接字和文件提供了异步操作。当然,所有操作都是非阻塞的,但对所有异步通道,你也可以执行阻塞操作,所有异步I/O操作都有下列两种形式中的一种:       </div>       <div>        <ul>         <li>第一个返回java.util.concurrent.Future,代表等待结果,你可以使用Future特性等待I/O操作结束;</li>         <li>第二个是使用CompletionHandler创建的,当操作结束时,如回调系统,调用这个处理程序。</li>        </ul>       </div>       <div>        下面是它们的一些例子,首先来看看使用Future的例子:        <pre class="brush:java; toolbar: true; auto-links: false;">AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("Path to file")); ByteBuffer buffer = ByteBuffer.allocate(capacity);   Future result = channel.read(buffer, 100); //Read capacity bytes from the file starting at position 100   boolean done = result.isDone(); //Indicate if the result is already terminated</pre>你也可以等待结束:        <pre class="brush:java; toolbar: true; auto-links: false;">int bytesRead = result.get();</pre>或等待超时:        <pre class="brush:java; toolbar: true; auto-links: false;">int bytesRead = result.get(10, TimeUnit.SECONDS); //Wait at most 10 seconds on the result</pre>再来看看使用CompletionHandler的例子:        <pre class="brush:java; toolbar: true; auto-links: false;">Future result = channel.read(buffer, 100, null, new CompletionHandler(){     public void completed(Integer result, Object attachement){         //Compute the result     }       public void failed(Throwable exception, Object attachement){         //Answer to the fail     } });</pre>正如你所看到的,你可以给操作一个附件,在操作末尾给CompletionHandler,当然,你可以把null当作一个附件提供,你可以传递任何你想传递的,如用于AsynchronousSocketChannel的Connection,或用于读操作的ByteBuffer。        <pre class="brush:java; toolbar: true; auto-links: false;">Future result = channel.read(buffer, 100, buffer, new CompletionHandler(){     public void completed(Integer result, ByteBuffer buffer){         //Compute the result     }       public void failed(Throwable exception, ByteBuffer buffer){         //Answer to the fail     } });</pre>        <div>         正如你所看到的,CompletionHandle也提供Future元素表示等待结果,因此你可以合并这两个格式。下面是NIO.2中的所有异步通道:        </div>        <div>         <ul>          <ul>           <li>AsynchronousFileChannel:读写文件的异步通道,这个通道没有全局位置,因此每个读写操作都需要一个位置,你可以使用不同的线程同时访问文件的不同部分,当你打开这个通道时,必须指定READ或WRITE选项;</li>           <li>AsynchronousSocketChannel:用于套接字的一个简单异步通道,连接、读/写、分散/聚集方法全都是异步的,读/写方法支持超时;</li>           <li>AsynchronousServerSocketChannel:用于ServerSocket的异步通道,accept()方法是异步的,当连接被接受时,调用CompletionHandler,这种连接的结果是一个AsynchronousSocketChannel;</li>           <li>AsynchronousDatagramChannel:用于数据报套接字的通道,读/写(连接)和接收/发送(无连接)方法是异步的。</li>          </ul>         </ul>        </div>        <div>         <br />        </div>        <h2>分组</h2>        <div>         当你使用AsynchronousChannels时,有线程调用完整的处理程序,这些线程被绑定到一个 AsynchronousChannelGroup组,这个组包含一个线程池,它封装了所有线程共享的资源,你可以使用线程池来调用这些组,AsynchronousFileChannel可以使用它自己的组创建,将ExecutorService作为一个参数传递给open()方法,在 open方法中,通道是使用AsynchronousChannelGroup创建的,如果你不给它一个组,或传递一个NULL,它就会使用默认组。通道被认为是属于组的,因此,如果组关闭了,通道也就关闭了。你可以使用ThreadFactory创建一个组:         <pre class="brush:java; toolbar: true; auto-links: false;">ThreadFactory myThreadFactory = Executors.defaultThreadFactory();   AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(25, threadFactory);</pre>或使用一个ExecutorService:         <pre class="brush:java; toolbar: true; auto-links: false;">ExecutorService service = Executors.newFixedThreadPool(25);  AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(service);</pre>而且你可以很容易地使用它:         <pre class="brush:java; toolbar: true; auto-links: false;">AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open(channelGroup);</pre>         <div>          你可以使用在组上使用shutdown()方法关闭组,关闭之后,你就不能使用这个组创建更多的通道,当所有通道关闭后,组也终止了,处理程序结束,资源也释放了。         </div>         <div>          当你使用任何类型的池和CompletionHandler时,你必须要注意一点,不要在CompletionHandler内使用阻塞或长时间操作,如果所有线程都被阻塞,整个应用程序都会被阻塞掉。如果你有自定义或缓存的线程池,它会使队列无限制地增长,最终导致OutOfMemoryError。         </div>         <div>          我想我把新的异步I/O API涵盖的内容讲得差不多了,当然这不是一两句话可以说清楚的,也不是每一个人都会使用到它们,但在某些时候它确实很有用,Java支持这种I/O操作终归是一件好事。如果我的代码中有什么错误我表示道歉,因为我也是刚刚才接触。         </div>         <div>          英文原文:          <a href="/misc/goto?guid=4959499162620492305" rel="nofollow" target="_blank">Java 7 : New I/O features (Asynchronous operations, multicasting, random access) with JSR 203 (NIO.2)</a>         </div>         <div>          中文原文:          <a href="/misc/goto?guid=4959499162711943840" rel="nofollow" target="_blank">51CTO</a>         </div>        </div>       </div>      </div>     </div>    </div>