summaryrefslogtreecommitdiff
path: root/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java
blob: 685e06afb16a0e1f82056b92467d361b878229ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.elasticsearch.common.util.concurrent;

import org.elasticsearch.common.Priority;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

/**
 *
 */
public class PrioritizedExecutorsTests extends ESTestCase {
    public void testPriorityQueue() throws Exception {
        PriorityBlockingQueue<Priority> queue = new PriorityBlockingQueue<>();
        List<Priority> priorities = Arrays.asList(Priority.values());
        Collections.shuffle(priorities, random());

        for (Priority priority : priorities) {
            queue.add(priority);
        }

        Priority prevPriority = null;
        while (!queue.isEmpty()) {
            if (prevPriority == null) {
                prevPriority = queue.poll();
            } else {
                assertThat(queue.poll().after(prevPriority), is(true));
            }
        }
    }

    public void testSubmitPrioritizedExecutorWithRunnables() throws Exception {
        ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        List<Integer> results = new ArrayList<>(8);
        CountDownLatch awaitingLatch = new CountDownLatch(1);
        CountDownLatch finishedLatch = new CountDownLatch(8);
        executor.submit(new AwaitingJob(awaitingLatch));
        executor.submit(new Job(7, Priority.LANGUID, results, finishedLatch));
        executor.submit(new Job(5, Priority.LOW, results, finishedLatch));
        executor.submit(new Job(2, Priority.HIGH, results, finishedLatch));
        executor.submit(new Job(6, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo)
        executor.submit(new Job(1, Priority.URGENT, results, finishedLatch));
        executor.submit(new Job(4, Priority.NORMAL, results, finishedLatch));
        executor.submit(new Job(3, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo)
        executor.submit(new Job(0, Priority.IMMEDIATE, results, finishedLatch));
        awaitingLatch.countDown();
        finishedLatch.await();

        assertThat(results.size(), equalTo(8));
        assertThat(results.get(0), equalTo(0));
        assertThat(results.get(1), equalTo(1));
        assertThat(results.get(2), equalTo(2));
        assertThat(results.get(3), equalTo(3));
        assertThat(results.get(4), equalTo(4));
        assertThat(results.get(5), equalTo(5));
        assertThat(results.get(6), equalTo(6));
        assertThat(results.get(7), equalTo(7));
        terminate(executor);
    }

    public void testExecutePrioritizedExecutorWithRunnables() throws Exception {
        ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        List<Integer> results = new ArrayList<>(8);
        CountDownLatch awaitingLatch = new CountDownLatch(1);
        CountDownLatch finishedLatch = new CountDownLatch(8);
        executor.execute(new AwaitingJob(awaitingLatch));
        executor.execute(new Job(7, Priority.LANGUID, results, finishedLatch));
        executor.execute(new Job(5, Priority.LOW, results, finishedLatch));
        executor.execute(new Job(2, Priority.HIGH, results, finishedLatch));
        executor.execute(new Job(6, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo)
        executor.execute(new Job(1, Priority.URGENT, results, finishedLatch));
        executor.execute(new Job(4, Priority.NORMAL, results, finishedLatch));
        executor.execute(new Job(3, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo)
        executor.execute(new Job(0, Priority.IMMEDIATE, results, finishedLatch));
        awaitingLatch.countDown();
        finishedLatch.await();

        assertThat(results.size(), equalTo(8));
        assertThat(results.get(0), equalTo(0));
        assertThat(results.get(1), equalTo(1));
        assertThat(results.get(2), equalTo(2));
        assertThat(results.get(3), equalTo(3));
        assertThat(results.get(4), equalTo(4));
        assertThat(results.get(5), equalTo(5));
        assertThat(results.get(6), equalTo(6));
        assertThat(results.get(7), equalTo(7));
        terminate(executor);
    }

    public void testSubmitPrioritizedExecutorWithCallables() throws Exception {
        ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        List<Integer> results = new ArrayList<>(8);
        CountDownLatch awaitingLatch = new CountDownLatch(1);
        CountDownLatch finishedLatch = new CountDownLatch(8);
        executor.submit(new AwaitingJob(awaitingLatch));
        executor.submit(new CallableJob(7, Priority.LANGUID, results, finishedLatch));
        executor.submit(new CallableJob(5, Priority.LOW, results, finishedLatch));
        executor.submit(new CallableJob(2, Priority.HIGH, results, finishedLatch));
        executor.submit(new CallableJob(6, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo)
        executor.submit(new CallableJob(1, Priority.URGENT, results, finishedLatch));
        executor.submit(new CallableJob(4, Priority.NORMAL, results, finishedLatch));
        executor.submit(new CallableJob(3, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo)
        executor.submit(new CallableJob(0, Priority.IMMEDIATE, results, finishedLatch));
        awaitingLatch.countDown();
        finishedLatch.await();

        assertThat(results.size(), equalTo(8));
        assertThat(results.get(0), equalTo(0));
        assertThat(results.get(1), equalTo(1));
        assertThat(results.get(2), equalTo(2));
        assertThat(results.get(3), equalTo(3));
        assertThat(results.get(4), equalTo(4));
        assertThat(results.get(5), equalTo(5));
        assertThat(results.get(6), equalTo(6));
        assertThat(results.get(7), equalTo(7));
        terminate(executor);
    }

    public void testSubmitPrioritizedExecutorWithMixed() throws Exception {
        ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        List<Integer> results = new ArrayList<>(8);
        CountDownLatch awaitingLatch = new CountDownLatch(1);
        CountDownLatch finishedLatch = new CountDownLatch(8);
        executor.submit(new AwaitingJob(awaitingLatch));
        executor.submit(new CallableJob(7, Priority.LANGUID, results, finishedLatch));
        executor.submit(new Job(5, Priority.LOW, results, finishedLatch));
        executor.submit(new CallableJob(2, Priority.HIGH, results, finishedLatch));
        executor.submit(new Job(6, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo)
        executor.submit(new CallableJob(1, Priority.URGENT, results, finishedLatch));
        executor.submit(new Job(4, Priority.NORMAL, results, finishedLatch));
        executor.submit(new CallableJob(3, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo)
        executor.submit(new Job(0, Priority.IMMEDIATE, results, finishedLatch));
        awaitingLatch.countDown();
        finishedLatch.await();

        assertThat(results.size(), equalTo(8));
        assertThat(results.get(0), equalTo(0));
        assertThat(results.get(1), equalTo(1));
        assertThat(results.get(2), equalTo(2));
        assertThat(results.get(3), equalTo(3));
        assertThat(results.get(4), equalTo(4));
        assertThat(results.get(5), equalTo(5));
        assertThat(results.get(6), equalTo(6));
        assertThat(results.get(7), equalTo(7));
        terminate(executor);
    }

    public void testTimeout() throws Exception {
        ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(EsExecutors.daemonThreadFactory(getTestName()));
        PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        final CountDownLatch invoked = new CountDownLatch(1);
        final CountDownLatch block = new CountDownLatch(1);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    invoked.countDown();
                    block.await();
                } catch (InterruptedException e) {
                    fail();
                }
            }

            @Override
            public String toString() {
                return "the blocking";
            }
        });
        invoked.await();
        PrioritizedEsThreadPoolExecutor.Pending[] pending = executor.getPending();
        assertThat(pending.length, equalTo(1));
        assertThat(pending[0].task.toString(), equalTo("the blocking"));
        assertThat(pending[0].executing, equalTo(true));

        final AtomicBoolean executeCalled = new AtomicBoolean();
        final CountDownLatch timedOut = new CountDownLatch(1);
        executor.execute(new Runnable() {
                             @Override
                             public void run() {
                                 executeCalled.set(true);
                             }

                             @Override
                             public String toString() {
                                 return "the waiting";
                             }
                         }, timer, TimeValue.timeValueMillis(100) /* enough timeout to catch them in the pending list... */, new Runnable() {
                    @Override
                    public void run() {
                        timedOut.countDown();
                    }
                }
        );

        pending = executor.getPending();
        assertThat(pending.length, equalTo(2));
        assertThat(pending[0].task.toString(), equalTo("the blocking"));
        assertThat(pending[0].executing, equalTo(true));
        assertThat(pending[1].task.toString(), equalTo("the waiting"));
        assertThat(pending[1].executing, equalTo(false));

        assertThat(timedOut.await(2, TimeUnit.SECONDS), equalTo(true));
        block.countDown();
        Thread.sleep(100); // sleep a bit to double check that execute on the timed out update task is not called...
        assertThat(executeCalled.get(), equalTo(false));
        assertTrue(terminate(timer, executor));
    }

    public void testTimeoutCleanup() throws Exception {
        ThreadPool threadPool = new ThreadPool("test");
        final ScheduledThreadPoolExecutor timer = (ScheduledThreadPoolExecutor) threadPool.scheduler();
        final AtomicBoolean timeoutCalled = new AtomicBoolean();
        PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()));
        final CountDownLatch invoked = new CountDownLatch(1);
        executor.execute(new Runnable() {
                             @Override
                             public void run() {
                                 invoked.countDown();
                             }
                         }, timer, TimeValue.timeValueHours(1), new Runnable() {
                    @Override
                    public void run() {
                        // We should never get here
                        timeoutCalled.set(true);
                    }
                }
        );
        invoked.await();

        // the timeout handler is added post execution (and quickly cancelled). We have allow for this
        // and use assert busy
        assertBusy(new Runnable() {
            @Override
            public void run() {
                assertThat(timer.getQueue().size(), equalTo(0));
            }
        }, 5, TimeUnit.SECONDS);
        assertThat(timeoutCalled.get(), equalTo(false));
        assertTrue(terminate(executor));
        assertTrue(terminate(threadPool));
    }

    static class AwaitingJob extends PrioritizedRunnable {

        private final CountDownLatch latch;

        private AwaitingJob(CountDownLatch latch) {
            super(Priority.URGENT);
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    static class Job extends PrioritizedRunnable {

        private final int result;
        private final List<Integer> results;
        private final CountDownLatch latch;

        Job(int result, Priority priority, List<Integer> results, CountDownLatch latch) {
            super(priority);
            this.result = result;
            this.results = results;
            this.latch = latch;
        }

        @Override
        public void run() {
            results.add(result);
            latch.countDown();
        }
    }

    static class CallableJob extends PrioritizedCallable<Integer> {

        private final int result;
        private final List<Integer> results;
        private final CountDownLatch latch;

        CallableJob(int result, Priority priority, List<Integer> results, CountDownLatch latch) {
            super(priority);
            this.result = result;
            this.results = results;
            this.latch = latch;
        }

        @Override
        public Integer call() throws Exception {
            results.add(result);
            latch.countDown();
            return result;
        }

    }
}