原文地址:http://www.javaworld.com/article/2078654/java-se/java-se-five-ways-to-maximize-java-nio-and-nio-2.html

Java NIO -- the New Input/Output API package-- was introduced with J2SE 1.4 in 2002. Java NIO's purpose was to improve the programming of I/O-intensive chores on the Java platform. A decade later, many Java programmers still don't know how to make the best use of NIO, and even fewer are aware that Java SE 7 introduced More New Input/Output APIs (NIO.2). In this tutorial you'll find five easy examples that demonstrate the advantages of the NIO and NIO.2 packages in common Java programming scenarios.

The primary contribution of NIO and NIO.2 to the Java platform is to improve performance in one of the core areas of Java application development: input/output processing. Neither package is particularly easy to work with, nor are the New Input/Output APIs required for every Java I/O scenario. Used correctly, though, Java NIO and NIO.2 can slash the time required for some common I/O operations. That's the superpower of NIO and NIO.2, and this article presents five relatively simple ways to leverage it:

  1. Change notifiers (because everybody needs a listener)
  2. Selectors help multiplex
  3. Channels -- promise and reality
  4. Memory mapping -- where it counts
  5. Character encoding and searching

The NIO context

How is it that a 10-year-old enhancement is still the NewInput/Output package for Java? The reason is that for many working Java programmers the basic Java I/O operations are more than adequate. Most Java developers don't have to learn NIO for our daily work. Moreover, NIO isn't just a performance package. Instead, it's a heterogeneous collection of facilities related to Java I/O. NIO boosts Java application performance by getting "closer to the metal" of a Java program, meaning that the NIO and NIO.2 APIs expose lower-level-system operating-system (OS) entry points. The tradeoff of NIO is that it simultaneously gives us greater control over I/O and demands that we exercise more care than we would with basic I/O programming. Another aspect of NIO is its attention to application expressivity, which we'll play with in some of the exercises that follow.

Starting out with NIO and NIO.2

Plenty of good references are available for NIO -- see Resources for some selected links. For starting out with NIO and NIO.2, the Java 2 SDK Standard Edition (SE) documentation and Java SE 7 documentation are indispensable. In order to run the examples in this article you will need to be working with JDK 7 or greater.

For many developers the first encounter with NIO might happen during maintenance work: an application has correct functionality but is slow to respond, so someone suggests using NIO to accelerate it. NIO shines when it's used to boost processing performance, but its results will be closely tied to the underlying platform. (Note that NIO is platform dependent.) If you're using NIO for the first time, it will pay you to measure carefully. You might discover that NIO's ability to accelerate application performance depends not only on the OS, but on the specific JVM, host virtualization context, mass storage characteristics, and even data. Measurement can be tricky to generalize, however. Keep this in mind particularly if a mobile deployment is among your targets.

And now, without further ado, let's explore five important facilities of NIO and NIO.2.

1. Change notifiers (because everybody needs a listener)

Java application performance is the common draw for developers interested in NIO or NIO.2. In my experience, however, NIO.2's file change notifier is the most compelling (if under-sung) feature of the New Input/Output APIs.

Many enterprise-class applications need to take a specific action when:

  • A file is uploaded into an FTP folder
  • A configuration definition is changed
  • A draft document is updated
  • Another file-system event occurs

These are all examples of change notification or change response. In early versions of Java (and other languages), polling was typically the best way to detect change events. Polling is a particular kind of endless loop: check the file-system or other object, compare it to its last-known state, and, if there's no change, check back again after a brief interval, such as a hundred milliseconds or ten seconds. Continue the loop indefinitely.

NIO.2 gives us a better way to express change detection. Listing 1 is a simple example.

Listing 1. Change notification in NIO.2

importjava.nio.file.attribute.*;importjava.io.*;importjava.util.*;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.nio.file.StandardWatchEventKinds;importjava.nio.file.WatchEvent;importjava.nio.file.WatchKey;importjava.nio.file.WatchService;importjava.util.List;publicclassWatcher{publicstaticvoidmain(String[]args){Paththis_dir =Paths.get(".");System.out.println("Now watching the current directory ...");try{WatchServicewatcher =this_dir.getFileSystem().newWatchService();this_dir.register(watcher,StandardWatchEventKinds.ENTRY_CREATE);WatchKeywatckKey =watcher.take();List<WatchEvent<&64;>>events =watckKey.pollEvents();for(WatchEventevent:events){System.out.println("Someone just created the file '"+event.context().toString()+"'.");}}catch(Exceptione){System.out.println("Error: "+e.toString());}}}

Compile this source, then launch the command-line executable. In the same directory, create a new file; you might, for example, touch example1, or even copy Watcher.class example1. You should see the following change notification message:

Someone just create the file 'example1'.

This simple example illustrates how to begin accessing NIO's language facilities in Java. It also introduces NIO.2'sWatcher class, which is considerably more straightforward and easy-to-use for change notification than the traditional I/O solution based on polling.

Watch for typos!

Be careful when you copy source from this article. Note, for instance, that theStandardWatchEventKinds object in Listing 1 is spelled as a plural. Even theJava.net documentation missed that!

Tip

NIO's notifiers are so much easier to use than the polling loops of old that it's tempting to neglect requirements analysis. But you should think through these semantics the first time you use a listener. Knowing when a file modification ends is more useful than knowing when it begins, for instance. That kind of analysis takes some care, especially in a common case like the FTP drop folder. NIO is a powerful package with some subtle "gotcha's"; it can punish a casual visitor.

2. Selectors and asynchronous I/O: Selectors help multiplex

Newcomers to NIO sometimes associate it with "non-blocking input/output." NIO is more than non-blocking I/O but the error makes sense: basic I/O in Java is blocking -- meaning that it waits until it can complete an operation -- whereas non-blocking, or asynchronous, I/O is one of the most-used NIO facilities.

NIO's non-blocking I/O is event-based, as demonstrated by the file-system listener in Listing 1. This means that a selector (or callback or listener) is defined for an I/O channel, then processing continues. When an event occurs on the selector -- when a line of input arrives, for instance -- the selector "wakes up" and executes. All of this is achieved within a single thread, which is a significant contrast to typical Java I/O.

Listing 2 demonstrates the use of NIO selectors in a multi-port networking echo-er, a program slightly modified from one created by Greg Travis in 2003 (see Resources). Unix and Unix-like operating systems have long had efficient implementations of selectors, so this sort of networking program is a model of good performance for a Java-coded networking program.

Listing 2. NIO selectors

importjava.io.*;importjava.net.*;importjava.nio.*;importjava.nio.channels.*;importjava.util.*;publicclassMultiPortEcho{privateintports[];privateByteBufferechoBuffer =ByteBuffer.allocate(1024);publicMultiPortEcho(intports[])throwsIOException{this.ports =ports;configure_selector();}privatevoidconfigure_selector()throwsIOException{// Create a new selectorSelectorselector =Selector.open();// Open a listener on each port, and register each one// with the selectorfor(inti=0;i<ports.length;++i){ServerSocketChannelssc =ServerSocketChannel.open();ssc.configureBlocking(false);ServerSocketss =ssc.socket();InetSocketAddressaddress =newInetSocketAddress(ports[i]);ss.bind(address);SelectionKeykey =ssc.register(selector,SelectionKey.OP_ACCEPT);System.out.println("Going to listen on "+ports[i]);}while(true){intnum =selector.select();SetselectedKeys =selector.selectedKeys();Iteratorit =selectedKeys.iterator();while(it.hasNext())

转载于:https://www.cnblogs.com/davidwang456/p/4758133.html

Five ways to maximize Java NIO and NIO.2--转相关推荐

  1. NIO详解(十三):Java IO 和NIO 总结

    1. 概述 下面总结了Java NIO和IO之间的主要差别 IO NIO 面向流 面向缓冲 阻塞IO 非阻塞IO 无 选择器 2. Java IO和 NIO的主要区别 2.1 面向流和面向缓冲区 Ja ...

  2. 【学习笔记】JAVA IO与NIO(new IO)的对比与不同IO模型的理解

    JAVA IO 分类: 几种IO 模型 1. 阻塞 IO 模型 2. 非阻塞 IO 模型 JAVA NIO 多路复用 IO 模型(即Java中的NIO) JAVA IO 思维导图: 分类: 按照流的方 ...

  3. Java NIO、NIO.2学习笔记

    http://www.cnblogs.com/littlehann/p/3720396.html 相关学习资料   http://www.molotang.com/articles/903.html ...

  4. Java IO(BIO, NIO, AIO) 总结

    文章转载自:JavaGuide 目录 BIO,NIO,AIO 总结 同步与异步 阻塞和非阻塞 1. BIO (Blocking I/O) 1.1 传统 BIO 1.2 伪异步 IO 1.3 代码示例 ...

  5. java中io.nio.aio_Java中网络IO的实现方式-BIO、NIO、AIO

    在网络编程中,接触到最多的就是利用Socket进行网络通信开发.在Java中主要是以下三种实现方式BIO.NIO.AIO. 关于这三个概念的辨析以前一直都是好像懂,但是表达的不是很清楚,下面做个总结完 ...

  6. java 修改最大nio连接数_关于java流的几个概念:IO、BIO、NIO、AIO,有几个人全知道?...

    关于同步.阻塞的知识我之前的文章有介绍,所以关于流用到这些概念与之前多线程用的概念一样. 下面具体来看看java中的几种流 IO/BIO BIO就是指IO,即传统的Blocking IO,即同步并阻塞 ...

  7. java 修改最大nio连接数_携程基于Quasar协程的NIO实践

    IO密集型系统在高并发场景下,会有大量线程处于阻塞状态,性能低下,JAVA上成熟的非阻塞IO(NIO)技术可解决该问题.目前Java项目对接NIO的方式主要依靠回调,代码复杂度高,降低了代码可读性与可 ...

  8. java中的NIO和IO到底是什么区别?20个问题告诉你答案

    摘要:NIO即New IO,这个库是在JDK1.4中才引入的.NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多. 本文分享自华为云社区<jav ...

  9. java输入输出流_金九银十准备季:Java异常+Java IO与NIO面试题(含答案)

    写在前面:2020年面试必备的Java后端进阶面试题总结了一份复习指南在Github上,内容详细,图文并茂,有需要学习的朋友可以Star一下! GitHub地址:abel-max/Java-Study ...

最新文章

  1. mysql不能改路径到d盘_Windows Server 2008 R2修改MySQL 5.5数据库目录为D盘示例
  2. 第十篇学会编写python代码_Python之路,第十篇:Python入门与基础10
  3. html5图片懒加载
  4. Win10双系统CentOS7安装完无法启动Win10的解决方法
  5. 局部敏感哈希-Locality Sensitive Hashing
  6. URAL 2047 Maths 打表 递推
  7. 阴阳师师徒系统不同服务器,阴阳师体服师徒系统未收录改为随机SSR
  8. 重磅分享:一份关于车贷的政策性文件分享
  9. 大唐电信[600198]股票
  10. java for 变量赋值_Java 如何引用变量赋值?
  11. 用emoji表情提交代码指南
  12. 国际计算机科学期刊,学术|16个国际顶尖计算机期刊介绍与作者教程
  13. dell t640 添加硬盘_Dell EMC PowerEdge T640详解
  14. html点击按钮弹出悬浮窗_html弹窗,html网页弹窗代码
  15. 测针对精密测量的重要性
  16. beautify插件实现.wxml文件属性自动换行
  17. 使用system备份ubuntu生成iso镜像
  18. 值得一看的电脑教程下载
  19. html如何使mp4成为背景,如何让MP4 video视频背景色变成透明?
  20. 图书馆炭火盆旁边的数学遐想

热门文章

  1. linux应用程序开发数据,《嵌入式linux应用程序开发详解》核心笔记
  2. c语言两个程序合并一起运行,这两个程序如何可以在一起运行
  3. Qt中的QTimer
  4. 繁星屠龙软件下载_历时72小时,测试5个软件,写出的数理化教学软件推荐……(下)...
  5. 边框回归的损失函数_一文搞懂常用的七种损失函数
  6. ansys结构分析单元与应用_结构动力学中的时域分析(3) —— 基于ANSYS的实现
  7. TabLayout+Viewpager+Fragment实现分页滚动
  8. linux区分用户的权限级别可用,如何限制Linux内核级别的特权用户访问?
  9. C++类模板(二)用类模板实现可变长数组
  10. keras 时间序列分析