1/*
2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/* @test
25 * @bug 8029516
26 * @summary Bash on WatchKey.cancel with a view to causing a crash when
27 *    an outstanding I/O operation on directory completes after the
28 *    directory has been closed
29 */
30import java.nio.file.ClosedWatchServiceException;
31import java.nio.file.FileSystems;
32import java.nio.file.Files;
33import java.nio.file.Path;
34import java.nio.file.Paths;
35import java.nio.file.WatchKey;
36import java.nio.file.WatchService;
37import static java.nio.file.StandardWatchEventKinds.*;
38import java.util.concurrent.ExecutorService;
39import java.util.concurrent.Executors;
40import java.util.concurrent.TimeUnit;
41
42public class LotsOfCancels {
43
44    // set to true for any exceptions
45    static volatile boolean failed;
46
47    public static void main(String[] args) throws Exception {
48
49        // create a bunch of directories. Create two tasks for each directory,
50        // one to bash on cancel, the other to poll the events
51        ExecutorService pool = Executors.newCachedThreadPool();
52        try {
53            Path testDir = Paths.get(System.getProperty("test.dir", "."));
54            Path top = Files.createTempDirectory(testDir, "LotsOfCancels");
55            for (int i=1; i<=16; i++) {
56                int id = i;
57                Path dir = Files.createDirectory(top.resolve("dir-" + i));
58                WatchService watcher = FileSystems.getDefault().newWatchService();
59                pool.submit(() -> handle(id, dir, watcher));
60                pool.submit(() -> poll(id, watcher));
61            }
62        } finally {
63            pool.shutdown();
64        }
65
66        // give thread pool lots of time to terminate
67        if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
68            throw new RuntimeException("Thread pool did not terminate");
69
70        if (failed)
71            throw new RuntimeException("Test failed, see log for details");
72    }
73
74    /**
75     * Stress the given WatchService, specifically the cancel method, in
76     * the given directory. Closes the WatchService when done.
77     */
78    static void handle(int id, Path dir, WatchService watcher) {
79        System.out.printf("begin handle %d%n", id);
80        try {
81            try {
82                Path file = dir.resolve("anyfile");
83                for (int i=0; i<2000; i++) {
84                    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
85                    Files.createFile(file);
86                    Files.delete(file);
87                    key.cancel();
88                }
89            } finally {
90                System.out.printf("WatchService %d closing ...%n", id);
91                watcher.close();
92                System.out.printf("WatchService %d closed %n", id);
93            }
94        } catch (Exception e) {
95            e.printStackTrace();
96            failed = true;
97        }
98        System.out.printf("end handle %d%n", id);
99    }
100
101    /**
102     * Polls the given WatchService in a tight loop. This keeps the event
103     * queue drained, it also hogs a CPU core which seems necessary to
104     * tickle the original bug.
105     */
106    static void poll(int id, WatchService watcher) {
107        System.out.printf("begin poll %d%n", id);
108        try {
109            for (;;) {
110                WatchKey key = watcher.take();
111                if (key != null) {
112                    key.pollEvents();
113                    key.reset();
114                }
115            }
116        } catch (ClosedWatchServiceException expected) {
117            // nothing to do but print
118            System.out.printf("poll %d expected exception %s%n", id, expected);
119        } catch (Exception e) {
120            e.printStackTrace();
121            failed = true;
122        }
123        System.out.printf("end poll %d%n", id);
124    }
125}
126