How many newWatchService can I create in Java 7?

669 Views Asked by At

How many newWatchService can I make ?

try{
    for(Path path : PathList) {
        watcher = path.getFileSystem().newWatchService();
    } catch (IOException e) {
        log.error(e);
    }
}

--> result: IOExeption: too many open files...

1

There are 1 best solutions below

0
On

I think you are supposed to create only one watcher service, but register [m]any paths to it.

As per the example given by Oracle docs (https://docs.oracle.com/javase/tutorial/essential/io/walk.html), there is only one watch service created, as a member variable of WatchDir class. Note the "this.watcher"

public class WatchDir {

    private final WatchService watcher;

elsewhere in the class...

 /**
 * Creates a WatchService and registers the given directory
  */
WatchDir(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();

The same service is used for registering all paths inside a given folder recursively.

Finally, the registration happens here...

/**
 * Register the given directory with the WatchService
 */
private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);