Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Five ways to maximize Java NIO and NIO.2

Build more responsive Java applications with the New Input/Output APIs

  • Print
  • Feedback

Page 2 of 5

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's Watcher 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 the StandardWatchEventKinds object in Listing 1 is spelled as a plural. Even the Java.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.

  • Print
  • Feedback

Resources