java.nio.file.ClosedWatchServiceException Java Examples

The following examples show how to use java.nio.file.ClosedWatchServiceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LotsOfCancels.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #2
Source File: LotsOfCancels.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(int id, WatchService watcher) {
    System.out.printf("begin poll %d%n", id);
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do but print
        System.out.printf("poll %d expected exception %s%n", id, expected);
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end poll %d%n", id);
}
 
Example #3
Source File: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #4
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #5
Source File: ConfigLoaderImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void handleChanges() {
    final WatchKey key;
    try {
        key = this.watchService.take();
    } catch (final InterruptedException | ClosedWatchServiceException e) {
        if (!ConfigLoaderImpl.this.closed) {
            LOG.warn(INTERRUPTED, e);
            Thread.currentThread().interrupt();
        }
        return;
    }

    if (key != null) {
        final List<String> fileNames = key.pollEvents()
                .stream().map(event -> event.context().toString())
                .collect(Collectors.toList());
        fileNames.forEach(this::handleEvent);

        final boolean reset = key.reset();
        if (!reset) {
            LOG.warn("Could not reset the watch key.");
        }
    }
}
 
Example #6
Source File: LotsOfCancels.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #7
Source File: LotsOfCancels.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #8
Source File: NioNotifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected String nextEvent() throws IOException, InterruptedException {
    WatchKey key;
    try {
        key = watcher.take();
    } catch (ClosedWatchServiceException cwse) { // #238261
        @SuppressWarnings({"ThrowableInstanceNotThrown"})
        InterruptedException ie = new InterruptedException();
        throw (InterruptedException) ie.initCause(cwse);
    }
    Path dir = (Path)key.watchable();
           
    String res = dir.toAbsolutePath().toString();
    for (WatchEvent<?> event: key.pollEvents()) {
        if (event.kind() == OVERFLOW) {
            // full rescan
            res = null;
        }
    }
    key.reset();
    return res;
}
 
Example #9
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #10
Source File: LotsOfCancels.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example #11
Source File: TestWatchService.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Test(expected=ClosedWatchServiceException.class)
@Ignore
public void testSimpleEx() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  
  WatchService watcher = rootPath.getFileSystem().newWatchService();
  rootPath.register(watcher, 
        new WatchEvent.Kind<?>[] { ENTRY_MODIFY });
  watcher.close();
  // Should throw ClosedWatchServiceException
  watcher.poll();
}
 
Example #12
Source File: ExternalEditor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("extedit");
    this.tmpfile = Files.createTempFile(dir, null, ".java");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (ClosedWatchServiceException ex) {
                // The watch service has been closed, we are done
                break;
            } catch (InterruptedException ex) {
                // tolerate an interrupt
                continue;
            }

            if (!key.pollEvents().isEmpty()) {
                saveFile();
            }

            boolean valid = key.reset();
            if (!valid) {
                // The watch service has been closed, we are done
                break;
            }
        }
    });
    watchedThread.start();
}
 
Example #13
Source File: FileSystemWatcher.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
void register(final Path path) throws IOException {
  if (meghanada.utils.FileUtils.filterFile(path.toFile())) {
    try {
      WatchKey key =
          path.register(
              this.watchService,
              StandardWatchEventKinds.ENTRY_CREATE,
              StandardWatchEventKinds.ENTRY_MODIFY,
              StandardWatchEventKinds.ENTRY_DELETE);
      this.watchKeys.put(key, path);
    } catch (ClosedWatchServiceException e) {
      log.warn(e.getMessage());
    }
  }
}
 
Example #14
Source File: ExternalEditor.java    From try-artifact with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("REPL");
    this.tmpfile = Files.createTempFile(dir, null, ".repl");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (ClosedWatchServiceException ex) {
                break;
            } catch (InterruptedException ex) {
                continue; // tolerate an intrupt
            }

            if (!key.pollEvents().isEmpty()) {
                if (!input.terminalEditorRunning()) {
                    saveFile();
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                errorHandler.accept("Invalid key");
                break;
            }
        }
    });
    watchedThread.start();
}
 
Example #15
Source File: JWatchService.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
@Override
public WatchKey poll()
{
  if (_isClosed.get()) {
    throw new ClosedWatchServiceException();
  }

  return _eventQueue.poll();
}
 
Example #16
Source File: AbstractWatchService.java    From directory-watcher with Apache License 2.0 5 votes vote down vote up
/** Returns the given key, throwing an exception if it's the poison. */
private WatchKey check(WatchKey key) {
  if (key == poison) {
    // ensure other blocking threads get the poison
    queue.offer(poison);
    throw new ClosedWatchServiceException();
  }
  return key;
}
 
Example #17
Source File: JWatchService.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
@Override
public WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException
{
  if (_isClosed.get()) {
    throw new ClosedWatchServiceException();
  }

  return _eventQueue.poll(timeout, unit);
}
 
Example #18
Source File: ExternalEditor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(final String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("REPL");
    this.tmpfile = Files.createTempFile(dir, null, ".js");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (final ClosedWatchServiceException ex) {
                break;
            } catch (final InterruptedException ex) {
                continue; // tolerate an intrupt
            }

            if (!key.pollEvents().isEmpty()) {
                if (!input.terminalEditorRunning()) {
                    saveFile();
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                errorHandler.accept("Invalid key");
                break;
            }
        }
    });
    watchedThread.start();
}
 
Example #19
Source File: LotsOfCloses.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a task that updates the registration of a directory with
 * a WatchService.
 */
static Callable<Boolean> newRegisterTask(WatchService watcher, Path dir) {
    return () -> {
        try {
            dir.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
            return true;
        } catch (ClosedWatchServiceException e) {
            return false;
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    };
}
 
Example #20
Source File: PollingWatchService.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private PollingWatchKey doPrivilegedRegister(Path path,
                                             Set<? extends WatchEvent.Kind<?>> events,
                                             int sensitivityInSeconds)
    throws IOException
{
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");

    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();

        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }

}
 
Example #21
Source File: JWatchService.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
@Override
public WatchKey take() throws InterruptedException
{
  if (_isClosed.get()) {
    throw new ClosedWatchServiceException();
  }

  return _eventQueue.take();
}
 
Example #22
Source File: PollingWatchService.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private PollingWatchKey doPrivilegedRegister(Path path,
                                             Set<? extends WatchEvent.Kind<?>> events,
                                             int sensitivityInSeconds)
    throws IOException
{
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");

    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();

        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }

}
 
Example #23
Source File: AbstractWatchService.java    From jimfs with Apache License 2.0 5 votes vote down vote up
/** Returns the given key, throwing an exception if it's the poison. */
@NullableDecl
private WatchKey check(@NullableDecl WatchKey key) {
  if (key == poison) {
    // ensure other blocking threads get the poison
    queue.offer(poison);
    throw new ClosedWatchServiceException();
  }
  return key;
}
 
Example #24
Source File: AbstractMergeWatcher.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void scanner ()
{
    logger.trace ( "Watching for events" );
    while ( true )
    {
        WatchKey key = null;
        try
        {
            key = this.ws.take ();
            logger.trace ( "Took events: {}", key.watchable () );

            final List<WatchEvent<?>> events = key.pollEvents ();
            for ( final WatchEvent<?> evt : events )
            {
                processEvent ( evt );
            }
        }
        catch ( final InterruptedException | ClosedWatchServiceException e )
        {
            return;
        }
        finally
        {
            if ( key != null )
            {
                key.reset ();
            }
        }
    }
}
 
Example #25
Source File: NioNotifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void removeWatch(WatchKey key) throws IOException {
    try {
        key.cancel();
    } catch (ClosedWatchServiceException ex) {
        // This happens on shutdown as watcher service can be closed before
        // all watches are removed from it. It is safe to swallow this
        // exception here.
    }
}
 
Example #26
Source File: NioNotifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected WatchKey addWatch(String pathStr) throws IOException {
    Path path = Paths.get(pathStr);
    try {
        WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        return key;
    } catch (ClosedWatchServiceException ex) {
        throw new IOException(ex);
    }
}
 
Example #27
Source File: BeatmapWatchService.java    From opsu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 */
private void processEvents() {
	while (true) {
		// wait for key to be signaled
		WatchKey key;
		try {
			key = watcher.take();
		} catch (InterruptedException | ClosedWatchServiceException e) {
			return;
		}

		Path dir = keys.get(key);
		if (dir == null)
			continue;

		boolean isPaused = paused;
		for (WatchEvent<?> event : key.pollEvents()) {
			WatchEvent.Kind<?> kind = event.kind();
			if (kind == StandardWatchEventKinds.OVERFLOW)
				continue;

			// context for directory entry event is the file name of entry
			WatchEvent<Path> ev = cast(event);
			Path name = ev.context();
			Path child = dir.resolve(name);
			//System.out.printf("%s: %s\n", kind.name(), child);

			// fire listeners
			if (!isPaused) {
				for (BeatmapWatchServiceListener listener : listeners)
					listener.eventReceived(kind, child);
			}

			// if directory is created, then register it and its sub-directories
			if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
				if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
					registerAll(child);
			}
		}

		// reset key and remove from set if directory no longer accessible
		if (!key.reset()) {
			keys.remove(key);
			if (keys.isEmpty())
				break;  // all directories are inaccessible
		}
	}
}
 
Example #28
Source File: AbstractWatchService.java    From directory-watcher with Apache License 2.0 4 votes vote down vote up
/** Checks that the watch service is open, throwing {@link ClosedWatchServiceException} if not. */
protected final void checkOpen() {
  if (!open.get()) {
    throw new ClosedWatchServiceException();
  }
}
 
Example #29
Source File: FileSystemAssetWatcher.java    From seventh with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param dir
 * @throws IOException
 */
public FileSystemAssetWatcher(File dir) throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    this.isActive = new AtomicBoolean(false);
    
    this.watchedAssets = new ConcurrentHashMap<File, WatchedAsset<?>>();
    this.pathToWatch = dir.toPath();
    
    this.watchService = fileSystem.newWatchService();
    this.watchThread = new Thread(new Runnable() {
        
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            while(isActive.get()) {
                try {
                    WatchKey key = watchService.take();
                    if(key.isValid()) {
                        List<WatchEvent<?>> events = key.pollEvents();
                        for(int i = 0; i < events.size(); i++) {
                            WatchEvent<?> event = events.get(i);
                            WatchEvent.Kind<?> kind = event.kind();
                            
                            /* ignore overflow events */
                            if(kind == StandardWatchEventKinds.OVERFLOW) {
                                continue;
                            }
                            
                            /* we are only listening for 'changed' events */
                            WatchEvent<Path> ev = (WatchEvent<Path>)event;
                            Path filename = ev.context();
                                                            
                            /* if we have a registered asset, lets go ahead and notify it */
                            WatchedAsset<?> watchedAsset = watchedAssets.get(new File(pathToWatch.toFile(), filename.toString()));
                            if(watchedAsset != null) {
                                try {
                                    watchedAsset.onAssetChanged();
                                }
                                catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    
                    key.reset();
                }
                catch (ClosedWatchServiceException e) {
                    break;
                }
                catch (InterruptedException e) {
                    break;
                }
            }
        }
    }, "watcher-thread");
    this.watchThread.setDaemon(true);
    
    this.pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
}
 
Example #30
Source File: UnixSshFileSystemWatchService.java    From jsch-nio with MIT License 4 votes vote down vote up
void ensureOpen() {
    if ( closed ) throw new ClosedWatchServiceException();
}