Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/nio/fs/PollingWatchService.java
38918 views
/*1* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.nio.fs;2627import java.nio.file.*;28import java.nio.file.attribute.*;29import java.security.AccessController;30import java.security.PrivilegedAction;31import java.security.PrivilegedExceptionAction;32import java.security.PrivilegedActionException;33import java.io.IOException;34import java.util.*;35import java.util.concurrent.*;36import com.sun.nio.file.SensitivityWatchEventModifier;3738/**39* Simple WatchService implementation that uses periodic tasks to poll40* registered directories for changes. This implementation is for use on41* operating systems that do not have native file change notification support.42*/4344class PollingWatchService45extends AbstractWatchService46{47// map of registrations48private final Map<Object,PollingWatchKey> map =49new HashMap<Object,PollingWatchKey>();5051// used to execute the periodic tasks that poll for changes52private final ScheduledExecutorService scheduledExecutor;5354PollingWatchService() {55// TBD: Make the number of threads configurable56scheduledExecutor = Executors57.newSingleThreadScheduledExecutor(new ThreadFactory() {58@Override59public Thread newThread(Runnable r) {60Thread t = new Thread(r);61t.setDaemon(true);62return t;63}});64}6566/**67* Register the given file with this watch service68*/69@Override70WatchKey register(final Path path,71WatchEvent.Kind<?>[] events,72WatchEvent.Modifier... modifiers)73throws IOException74{75// check events - CCE will be thrown if there are invalid elements76final Set<WatchEvent.Kind<?>> eventSet =77new HashSet<WatchEvent.Kind<?>>(events.length);78for (WatchEvent.Kind<?> event: events) {79// standard events80if (event == StandardWatchEventKinds.ENTRY_CREATE ||81event == StandardWatchEventKinds.ENTRY_MODIFY ||82event == StandardWatchEventKinds.ENTRY_DELETE)83{84eventSet.add(event);85continue;86}8788// OVERFLOW is ignored89if (event == StandardWatchEventKinds.OVERFLOW) {90continue;91}9293// null/unsupported94if (event == null)95throw new NullPointerException("An element in event set is 'null'");96throw new UnsupportedOperationException(event.name());97}98if (eventSet.isEmpty())99throw new IllegalArgumentException("No events to register");100101// A modifier may be used to specify the sensitivity level102SensitivityWatchEventModifier sensivity = SensitivityWatchEventModifier.MEDIUM;103if (modifiers.length > 0) {104for (WatchEvent.Modifier modifier: modifiers) {105if (modifier == null)106throw new NullPointerException();107if (modifier instanceof SensitivityWatchEventModifier) {108sensivity = (SensitivityWatchEventModifier)modifier;109continue;110}111throw new UnsupportedOperationException("Modifier not supported");112}113}114115// check if watch service is closed116if (!isOpen())117throw new ClosedWatchServiceException();118119// registration is done in privileged block as it requires the120// attributes of the entries in the directory.121try {122final SensitivityWatchEventModifier s = sensivity;123return AccessController.doPrivileged(124new PrivilegedExceptionAction<PollingWatchKey>() {125@Override126public PollingWatchKey run() throws IOException {127return doPrivilegedRegister(path, eventSet, s);128}129});130} catch (PrivilegedActionException pae) {131Throwable cause = pae.getCause();132if (cause != null && cause instanceof IOException)133throw (IOException)cause;134throw new AssertionError(pae);135}136}137138// registers directory returning a new key if not already registered or139// existing key if already registered140private PollingWatchKey doPrivilegedRegister(Path path,141Set<? extends WatchEvent.Kind<?>> events,142SensitivityWatchEventModifier sensivity)143throws IOException144{145// check file is a directory and get its file key if possible146BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);147if (!attrs.isDirectory()) {148throw new NotDirectoryException(path.toString());149}150Object fileKey = attrs.fileKey();151if (fileKey == null)152throw new AssertionError("File keys must be supported");153154// grab close lock to ensure that watch service cannot be closed155synchronized (closeLock()) {156if (!isOpen())157throw new ClosedWatchServiceException();158159PollingWatchKey watchKey;160synchronized (map) {161watchKey = map.get(fileKey);162if (watchKey == null) {163// new registration164watchKey = new PollingWatchKey(path, this, fileKey);165map.put(fileKey, watchKey);166} else {167// update to existing registration168watchKey.disable();169}170}171watchKey.enable(events, sensivity.sensitivityValueInSeconds());172return watchKey;173}174175}176177@Override178void implClose() throws IOException {179synchronized (map) {180for (Map.Entry<Object,PollingWatchKey> entry: map.entrySet()) {181PollingWatchKey watchKey = entry.getValue();182watchKey.disable();183watchKey.invalidate();184}185map.clear();186}187AccessController.doPrivileged(new PrivilegedAction<Void>() {188@Override189public Void run() {190scheduledExecutor.shutdown();191return null;192}193});194}195196/**197* Entry in directory cache to record file last-modified-time and tick-count198*/199private static class CacheEntry {200private long lastModified;201private int lastTickCount;202203CacheEntry(long lastModified, int lastTickCount) {204this.lastModified = lastModified;205this.lastTickCount = lastTickCount;206}207208int lastTickCount() {209return lastTickCount;210}211212long lastModified() {213return lastModified;214}215216void update(long lastModified, int tickCount) {217this.lastModified = lastModified;218this.lastTickCount = tickCount;219}220}221222/**223* WatchKey implementation that encapsulates a map of the entries of the224* entries in the directory. Polling the key causes it to re-scan the225* directory and queue keys when entries are added, modified, or deleted.226*/227private class PollingWatchKey extends AbstractWatchKey {228private final Object fileKey;229230// current event set231private Set<? extends WatchEvent.Kind<?>> events;232233// the result of the periodic task that causes this key to be polled234private ScheduledFuture<?> poller;235236// indicates if the key is valid237private volatile boolean valid;238239// used to detect files that have been deleted240private int tickCount;241242// map of entries in directory243private Map<Path,CacheEntry> entries;244245PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey)246throws IOException247{248super(dir, watcher);249this.fileKey = fileKey;250this.valid = true;251this.tickCount = 0;252this.entries = new HashMap<Path,CacheEntry>();253254// get the initial entries in the directory255try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {256for (Path entry: stream) {257// don't follow links258long lastModified =259Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();260entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount));261}262} catch (DirectoryIteratorException e) {263throw e.getCause();264}265}266267Object fileKey() {268return fileKey;269}270271@Override272public boolean isValid() {273return valid;274}275276void invalidate() {277valid = false;278}279280// enables periodic polling281void enable(Set<? extends WatchEvent.Kind<?>> events, long period) {282synchronized (this) {283// update the events284this.events = events;285286// create the periodic task287Runnable thunk = new Runnable() { public void run() { poll(); }};288this.poller = scheduledExecutor289.scheduleAtFixedRate(thunk, period, period, TimeUnit.SECONDS);290}291}292293// disables periodic polling294void disable() {295synchronized (this) {296if (poller != null)297poller.cancel(false);298}299}300301@Override302public void cancel() {303valid = false;304synchronized (map) {305map.remove(fileKey());306}307disable();308}309310/**311* Polls the directory to detect for new files, modified files, or312* deleted files.313*/314synchronized void poll() {315if (!valid) {316return;317}318319// update tick320tickCount++;321322// open directory323DirectoryStream<Path> stream = null;324try {325stream = Files.newDirectoryStream(watchable());326} catch (IOException x) {327// directory is no longer accessible so cancel key328cancel();329signal();330return;331}332333// iterate over all entries in directory334try {335for (Path entry: stream) {336long lastModified = 0L;337try {338lastModified =339Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();340} catch (IOException x) {341// unable to get attributes of entry. If file has just342// been deleted then we'll report it as deleted on the343// next poll344continue;345}346347// lookup cache348CacheEntry e = entries.get(entry.getFileName());349if (e == null) {350// new file found351entries.put(entry.getFileName(),352new CacheEntry(lastModified, tickCount));353354// queue ENTRY_CREATE if event enabled355if (events.contains(StandardWatchEventKinds.ENTRY_CREATE)) {356signalEvent(StandardWatchEventKinds.ENTRY_CREATE, entry.getFileName());357continue;358} else {359// if ENTRY_CREATE is not enabled and ENTRY_MODIFY is360// enabled then queue event to avoid missing out on361// modifications to the file immediately after it is362// created.363if (events.contains(StandardWatchEventKinds.ENTRY_MODIFY)) {364signalEvent(StandardWatchEventKinds.ENTRY_MODIFY, entry.getFileName());365}366}367continue;368}369370// check if file has changed371if (e.lastModified != lastModified) {372if (events.contains(StandardWatchEventKinds.ENTRY_MODIFY)) {373signalEvent(StandardWatchEventKinds.ENTRY_MODIFY,374entry.getFileName());375}376}377// entry in cache so update poll time378e.update(lastModified, tickCount);379380}381} catch (DirectoryIteratorException e) {382// ignore for now; if the directory is no longer accessible383// then the key will be cancelled on the next poll384} finally {385386// close directory stream387try {388stream.close();389} catch (IOException x) {390// ignore391}392}393394// iterate over cache to detect entries that have been deleted395Iterator<Map.Entry<Path,CacheEntry>> i = entries.entrySet().iterator();396while (i.hasNext()) {397Map.Entry<Path,CacheEntry> mapEntry = i.next();398CacheEntry entry = mapEntry.getValue();399if (entry.lastTickCount() != tickCount) {400Path name = mapEntry.getKey();401// remove from map and queue delete event (if enabled)402i.remove();403if (events.contains(StandardWatchEventKinds.ENTRY_DELETE)) {404signalEvent(StandardWatchEventKinds.ENTRY_DELETE, name);405}406}407}408}409}410}411412413