原文地址:http://www.javaworld.com/article/2078654/java-se/java-se-five-ways-to-maximize-java-nio-and-nio-2.htmlhtml
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.java
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:ios
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.express
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.api
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.promise
And now, without further ado, let's explore five important facilities of NIO and NIO.2.oracle
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.app
Many enterprise-class applications need to take a specific action when:less
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.dom
NIO.2 gives us a better way to express change detection. Listing 1 is a simple example.
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.
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!
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.
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.
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())