日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Five ways to maximize Java NIO and NIO.2--转

發布時間:2025/4/5 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Five ways to maximize Java NIO and NIO.2--转 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文地址: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:

  • Change notifiers (because everybody needs a listener)
  • Selectors help multiplex
  • Channels -- promise and reality
  • Memory mapping -- where it counts
  • 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

    import java.nio.file.attribute.*; import java.io.*; import java.util.*; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.List; public class Watcher { public static void main(String[] args) { Path this_dir = Paths.get("."); System.out.println("Now watching the current directory ..."); try { WatchService watcher = this_dir.getFileSystem().newWatchService(); this_dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); WatchKey watckKey = watcher.take(); List<WatchEvent< &64;>> events = watckKey.pollEvents(); for (WatchEvent event : events) { System.out.println("Someone just created the file '" + event.context().toString() + "'."); } } catch (Exception e) { 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

    import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.*; public class MultiPortEcho { private int ports[]; private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 ); public MultiPortEcho( int ports[] ) throws IOException { this.ports = ports; configure_selector(); } private void configure_selector() throws IOException { // Create a new selector Selector selector = Selector.open(); // Open a listener on each port, and register each one // with the selector for (int i=0; i<ports.length; ++i) { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss = ssc.socket(); InetSocketAddress address = new InetSocketAddress(ports[i]); ss.bind(address); SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Going to listen on " + ports[i]); } while (true) { int num = selector.select(); Set selectedKeys = selector.selectedKeys(); Iterator it = selectedKeys.iterator(); while (it.hasNext())

    轉載于:https://www.cnblogs.com/davidwang456/p/4758133.html

    總結

    以上是生活随笔為你收集整理的Five ways to maximize Java NIO and NIO.2--转的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。