オーバーフローのドキュメントには次のように記載されています。
OVERFLOW – イベントが失われたか破棄された可能性があることを示します。
どのような状況でイベントが失われたり破棄されたりすることを期待すべきかについては述べていませんか? 最初は、フォルダーに大量のファイルを非常に高速に書き込んだ結果だと思いました。サイズがゼロの数千のファイルを作成し、監視対象のディレクトリに移動しました。オーバーフローなし。
私は何が欠けていますか?
オーバーフローを生成する最小限の例
watcherService.register
の前後にファイルを作成するだけですwatcherService.take
。
次のように呼び出します。
java Overflow 256
イベントの数を制御します。
Java 7 および Ubuntu 14.04 は、512 イベントで最大になります。
オーバーフローが発生するたびに、 によって 1 つのイベントだけが返されましたpollEvents()
が、これは Javadoc で明確に指定されていません。
次のことを考えると、この制限が非常に小さいのは奇妙だと思います。
sysctl fs.inotify.max_user_watches
は524288
inotify
Linux で使用されているようです。コード:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchService;
import java.util.List;
public class Overflow {
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
public static void main(final String[] args) throws InterruptedException, IOException {
int nfiles;
if (args.length > 0)
nfiles = Integer.parseInt(args[0]);
else
nfiles = 10_000;
Path directory = Files.createTempDirectory("watch-service-overflow");
final WatchService watchService = FileSystems.getDefault().newWatchService();
directory.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
final Path p = directory.resolve(Paths.get("Hello World!"));
for (int i = 0; i < nfiles; i++) {
Files.createFile(p);
Files.delete(p);
}
List<WatchEvent<?>> events = watchService.take().pollEvents();
for (final WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
System.out.println("Overflow.");
System.out.println("Number of events: " + events.size());
return;
}
}
System.out.println("No overflow.");
Files.delete(directory);
}
}