Path: blob/master/test/jdk/java/nio/file/WatchService/LotsOfEvents.java
66645 views
/*1* Copyright (c) 2010, 2021, 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 6907760 6929532 817481925* @summary Tests WatchService behavior when lots of events are pending (use -Dseed=X to set PRNG seed)26* @library ..27* @library /test/lib28* @build jdk.test.lib.RandomFactory29* @run main/timeout=180 LotsOfEvents30* @key randomness31*/3233import java.io.IOException;34import java.io.OutputStream;35import java.nio.file.*;36import static java.nio.file.StandardWatchEventKinds.*;37import java.util.*;38import java.util.concurrent.TimeUnit;39import java.util.stream.Collectors;4041import jdk.test.lib.RandomFactory;4243public class LotsOfEvents {4445private static final Random RAND = RandomFactory.getRandom();4647public static void main(String[] args) throws Exception {48Path dir = TestUtil.createTemporaryDirectory();49try {50testOverflowEvent(dir);51testModifyEventsQueuing(dir);52} finally {53TestUtil.removeAll(dir);54}55}5657/**58* Tests that OVERFLOW events are not retreived with other events.59*/60static void testOverflowEvent(Path dir)61throws IOException, InterruptedException62{63try (WatchService watcher = dir.getFileSystem().newWatchService()) {64dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);6566// create a lot of files67int n = 1024;68Path[] files = new Path[n];69for (int i=0; i<n; i++) {70files[i] = Files.createFile(dir.resolve("foo" + i));71}7273// give time for events to accumulate (improve chance of overflow)74Thread.sleep(1000);7576// check that we see the create events (or overflow)77drainAndCheckOverflowEvents(dir, watcher, ENTRY_CREATE, n);7879// delete the files80for (int i=0; i<n; i++) {81Files.delete(files[i]);82}8384// give time for events to accumulate (improve chance of overflow)85Thread.sleep(1000);8687// check that we see the delete events (or overflow)88drainAndCheckOverflowEvents(dir, watcher, ENTRY_DELETE, n);89}90}9192static void drainAndCheckOverflowEvents(Path dir,93WatchService watcher,94WatchEvent.Kind<?> expectedKind,95int count)96throws IOException, InterruptedException97{98// wait for key to be signalled - the timeout is long to allow for99// polling implementations100WatchKey key = watcher.poll(15, TimeUnit.SECONDS);101if (key != null && count == 0)102throw new RuntimeException("Key was signalled (unexpected)");103if (key == null && count > 0)104throw new RuntimeException("Key not signalled (unexpected)");105106int nread = 0;107boolean gotOverflow = false;108while (key != null) {109List<WatchEvent<?>> events = key.pollEvents();110System.out.println("Polling retrieved " + events.size() + " event(s)");111for (WatchEvent<?> event: events) {112WatchEvent.Kind<?> kind = event.kind();113if (kind == expectedKind) {114// expected event kind115if (++nread > count)116throw new RuntimeException("More events than expected!!");117} else if (kind == OVERFLOW) {118// overflow event should not be retrieved with other events119if (events.size() > 1)120throw new RuntimeException("Overflow retrieved with other events");121gotOverflow = true;122} else {123throw new RuntimeException("Unexpected event '" + kind + "'");124}125}126if (!key.reset())127throw new RuntimeException("Key is no longer valid");128key = watcher.poll(15, TimeUnit.SECONDS);129}130131// check that all expected events were received or there was an overflow132if (nread < count && !gotOverflow) {133System.err.printf("Test directory %s contains %d files%n",134dir, Files.list(dir).count());135136// the additional polling here is just for diagnostics and doesn't137// change the test result (which is a failed test)138long timeBeforePoll = System.nanoTime();139key = watcher.poll(15, TimeUnit.SECONDS);140long timeAfterPoll = System.nanoTime();141if (key == null) {142System.err.println("key still null after extra polling");143} else {144List<WatchEvent<?>> events = key.pollEvents();145System.err.printf("Retrieved key with %d events after %d ns%n",146events.size(), timeAfterPoll - timeBeforePoll);147// count for each kind of event148Map<WatchEvent.Kind, Long> countPerEventType = events.stream()149.collect(Collectors.groupingBy(WatchEvent::kind, Collectors.counting()));150countPerEventType.forEach((kind, num)151-> System.err.println(num + " events of type " + kind));152}153154throw new RuntimeException("Insufficient "155+ expectedKind.name() + " events: expected "156+ count + ", received " + nread);157}158}159160/**161* Tests that check that ENTRY_MODIFY events are queued efficiently162*/163static void testModifyEventsQueuing(Path dir)164throws IOException, InterruptedException165{166// this test uses a random number of files167final int nfiles = 5 + RAND.nextInt(10);168DirectoryEntry[] entries = new DirectoryEntry[nfiles];169for (int i=0; i<nfiles; i++) {170entries[i] = new DirectoryEntry(dir.resolve("foo" + i));171172// "some" of the files exist, some do not.173entries[i].deleteIfExists();174if (RAND.nextBoolean())175entries[i].create();176}177178try (WatchService watcher = dir.getFileSystem().newWatchService()) {179dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);180181// do several rounds of noise and test182for (int round=0; round<10; round++) {183184// make some noise!!!185for (int i=0; i<100; i++) {186DirectoryEntry entry = entries[RAND.nextInt(nfiles)];187int action = RAND.nextInt(10);188switch (action) {189case 0 : entry.create(); break;190case 1 : entry.deleteIfExists(); break;191default: entry.modifyIfExists();192}193}194195// process events and ensure that we don't get repeated modify196// events for the same file.197WatchKey key = watcher.poll(15, TimeUnit.SECONDS);198while (key != null) {199Set<Path> modified = new HashSet<>();200for (WatchEvent<?> event: key.pollEvents()) {201WatchEvent.Kind<?> kind = event.kind();202Path file = (kind == OVERFLOW) ? null : (Path)event.context();203if (kind == ENTRY_MODIFY) {204boolean added = modified.add(file);205if (!added) {206throw new RuntimeException(207"ENTRY_MODIFY events not queued efficiently");208}209} else {210if (file != null) modified.remove(file);211}212}213if (!key.reset())214throw new RuntimeException("Key is no longer valid");215key = watcher.poll(2, TimeUnit.SECONDS);216}217}218}219}220221static class DirectoryEntry {222private final Path file;223DirectoryEntry(Path file) {224this.file = file;225}226void create() throws IOException {227if (Files.notExists(file))228Files.createFile(file);229230}231void deleteIfExists() throws IOException {232Files.deleteIfExists(file);233}234void modifyIfExists() throws IOException {235if (Files.exists(file)) {236try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.APPEND)) {237out.write("message".getBytes());238}239}240}241}242243}244245246