1/*
2 * Copyright (c) 2005, 2010, 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/*
25 * @test
26 * @bug 6316155 6595669 6871697 6868712
27 * @summary Test concurrent offer vs. remove
28 * @run main OfferRemoveLoops 300
29 * @author Martin Buchholz
30 */
31
32import static java.util.concurrent.TimeUnit.MILLISECONDS;
33
34import java.util.Arrays;
35import java.util.Queue;
36import java.util.SplittableRandom;
37import java.util.concurrent.ArrayBlockingQueue;
38import java.util.concurrent.CountDownLatch;
39import java.util.concurrent.ConcurrentLinkedDeque;
40import java.util.concurrent.ConcurrentLinkedQueue;
41import java.util.concurrent.LinkedBlockingDeque;
42import java.util.concurrent.LinkedBlockingQueue;
43import java.util.concurrent.LinkedTransferQueue;
44import java.util.concurrent.PriorityBlockingQueue;
45import java.util.concurrent.Semaphore;
46
47@SuppressWarnings({"unchecked", "rawtypes", "deprecation"})
48public class OfferRemoveLoops {
49    final long testDurationMillisDefault = 10L * 1000L;
50    final long testDurationMillis;
51
52    OfferRemoveLoops(String[] args) {
53        testDurationMillis = (args.length > 0) ?
54            Long.valueOf(args[0]) : testDurationMillisDefault;
55    }
56
57    void checkNotContainsNull(Iterable it) {
58        for (Object x : it)
59            check(x != null);
60    }
61
62    void test(String[] args) throws Throwable {
63        testQueue(new LinkedBlockingQueue(10));
64        testQueue(new LinkedBlockingQueue());
65        testQueue(new LinkedBlockingDeque(10));
66        testQueue(new LinkedBlockingDeque());
67        testQueue(new ArrayBlockingQueue(10));
68        testQueue(new PriorityBlockingQueue(10));
69        testQueue(new ConcurrentLinkedDeque());
70        testQueue(new ConcurrentLinkedQueue());
71        testQueue(new LinkedTransferQueue());
72    }
73
74    void testQueue(final Queue q) throws Throwable {
75        System.err.println(q.getClass().getSimpleName());
76        final long testDurationNanos = testDurationMillis * 1000L * 1000L;
77        final long quittingTimeNanos = System.nanoTime() + testDurationNanos;
78        final long timeoutMillis = 10L * 1000L;
79        final int maxChunkSize = 1042;
80        final int maxQueueSize = 10 * maxChunkSize;
81        final CountDownLatch done = new CountDownLatch(3);
82        final SplittableRandom rnd = new SplittableRandom();
83
84        /** Poor man's bounded buffer; prevents unbounded queue expansion. */
85        final Semaphore offers = new Semaphore(maxQueueSize);
86
87        abstract class CheckedThread extends Thread {
88            final SplittableRandom rnd;
89
90            CheckedThread(String name, SplittableRandom rnd) {
91                super(name);
92                this.rnd = rnd;
93                setDaemon(true);
94                start();
95            }
96            /** Polls for quitting time. */
97            protected boolean quittingTime() {
98                return System.nanoTime() - quittingTimeNanos > 0;
99            }
100            /** Polls occasionally for quitting time. */
101            protected boolean quittingTime(long i) {
102                return (i % 1024) == 0 && quittingTime();
103            }
104            protected abstract void realRun() throws Exception;
105            public void run() {
106                try { realRun(); } catch (Throwable t) { unexpected(t); }
107            }
108        }
109
110        Thread offerer = new CheckedThread("offerer", rnd.split()) {
111            protected void realRun() throws InterruptedException {
112                final int chunkSize = rnd.nextInt(maxChunkSize) + 20;
113                long c = 0;
114                while (! quittingTime()) {
115                    if (q.offer(Long.valueOf(c))) {
116                        if ((++c % chunkSize) == 0) {
117                            offers.acquire(chunkSize);
118                        }
119                    } else {
120                        Thread.yield();
121                    }
122                }
123                done.countDown();
124            }};
125
126        Thread remover = new CheckedThread("remover", rnd.split()) {
127            protected void realRun() {
128                final int chunkSize = rnd.nextInt(maxChunkSize) + 20;
129                long c = 0;
130                while (! quittingTime()) {
131                    if (q.remove(Long.valueOf(c))) {
132                        if ((++c % chunkSize) == 0) {
133                            offers.release(chunkSize);
134                        }
135                    } else {
136                        Thread.yield();
137                    }
138                }
139                q.clear();
140                offers.release(1<<30);  // Releases waiting offerer thread
141                done.countDown();
142            }};
143
144        Thread scanner = new CheckedThread("scanner", rnd.split()) {
145            protected void realRun() {
146                while (! quittingTime()) {
147                    switch (rnd.nextInt(3)) {
148                    case 0: checkNotContainsNull(q); break;
149                    case 1: q.size(); break;
150                    case 2: checkNotContainsNull
151                            (Arrays.asList(q.toArray(new Long[0])));
152                        break;
153                    }
154                    Thread.yield();
155                }
156                done.countDown();
157            }};
158
159        if (! done.await(timeoutMillis + testDurationMillis, MILLISECONDS)) {
160            for (Thread thread : new Thread[] { offerer, remover, scanner }) {
161                if (thread.isAlive()) {
162                    System.err.printf("Hung thread: %s%n", thread.getName());
163                    failed++;
164                    for (StackTraceElement e : thread.getStackTrace())
165                        System.err.println(e);
166                    thread.interrupt();
167                }
168            }
169        }
170    }
171
172    //--------------------- Infrastructure ---------------------------
173    volatile int passed = 0, failed = 0;
174    void pass() {passed++;}
175    void fail() {failed++; Thread.dumpStack();}
176    void fail(String msg) {System.err.println(msg); fail();}
177    void unexpected(Throwable t) {failed++; t.printStackTrace();}
178    void check(boolean cond) {if (cond) pass(); else fail();}
179    void equal(Object x, Object y) {
180        if (x == null ? y == null : x.equals(y)) pass();
181        else fail(x + " not equal to " + y);}
182    public static void main(String[] args) throws Throwable {
183        new OfferRemoveLoops(args).instanceMain(args);}
184    public void instanceMain(String[] args) throws Throwable {
185        try {test(args);} catch (Throwable t) {unexpected(t);}
186        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
187        if (failed > 0) throw new AssertionError("Some tests failed");}
188}
189