aboutsummaryrefslogtreecommitdiff
path: root/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java
blob: cbb6c1c827e17b83cccf9ef05ce04f25bb5514bb (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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
 * Copyright (C) 2008 The Guava Authors
 *
 * Licensed 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 com.google.common.util.concurrent;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.util.concurrent.MoreExecutors.newSequentialExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;

/**
 * Tests {@link SequentialExecutor}.
 *
 * @author JJ Furman
 */
public class SequentialExecutorTest extends TestCase {

  private static class FakeExecutor implements Executor {
    Queue<Runnable> tasks = Queues.newArrayDeque();

    @Override
    public void execute(Runnable command) {
      tasks.add(command);
    }

    boolean hasNext() {
      return !tasks.isEmpty();
    }

    void runNext() {
      assertTrue("expected at least one task to run", hasNext());
      tasks.remove().run();
    }

    void runAll() {
      while (hasNext()) {
        runNext();
      }
    }
  }

  private FakeExecutor fakePool;
  private SequentialExecutor e;

  @Override
  public void setUp() {
    fakePool = new FakeExecutor();
    e = new SequentialExecutor(fakePool);
  }

  public void testConstructingWithNullExecutor_fails() {
    try {
      new SequentialExecutor(null);
      fail("Should have failed with NullPointerException.");
    } catch (NullPointerException expected) {
    }
  }

  public void testBasics() {
    final AtomicInteger totalCalls = new AtomicInteger();
    Runnable intCounter =
        new Runnable() {
          @Override
          public void run() {
            totalCalls.incrementAndGet();
            // Make sure that no other tasks are scheduled to run while this is running.
            assertFalse(fakePool.hasNext());
          }
        };

    assertFalse(fakePool.hasNext());
    e.execute(intCounter);
    // A task should have been scheduled
    assertTrue(fakePool.hasNext());
    e.execute(intCounter);
    // Our executor hasn't run any tasks yet.
    assertEquals(0, totalCalls.get());
    fakePool.runAll();
    assertEquals(2, totalCalls.get());
    // Queue is empty so no runner should be scheduled.
    assertFalse(fakePool.hasNext());

    // Check that execute can be safely repeated
    e.execute(intCounter);
    e.execute(intCounter);
    e.execute(intCounter);
    // No change yet.
    assertEquals(2, totalCalls.get());
    fakePool.runAll();
    assertEquals(5, totalCalls.get());
    assertFalse(fakePool.hasNext());
  }

  public void testOrdering() {
    final List<Integer> callOrder = Lists.newArrayList();

    class FakeOp implements Runnable {
      final int op;

      FakeOp(int op) {
        this.op = op;
      }

      @Override
      public void run() {
        callOrder.add(op);
      }
    }

    e.execute(new FakeOp(0));
    e.execute(new FakeOp(1));
    e.execute(new FakeOp(2));
    fakePool.runAll();

    assertEquals(ImmutableList.of(0, 1, 2), callOrder);
  }

  public void testRuntimeException_doesNotStopExecution() {

    final AtomicInteger numCalls = new AtomicInteger();

    Runnable runMe =
        new Runnable() {
          @Override
          public void run() {
            numCalls.incrementAndGet();
            throw new RuntimeException("FAKE EXCEPTION!");
          }
        };

    e.execute(runMe);
    e.execute(runMe);
    fakePool.runAll();

    assertEquals(2, numCalls.get());
  }

  public void testInterrupt_beforeRunRestoresInterruption() throws Exception {
    // Run a task on the composed Executor that interrupts its thread (i.e. this thread).
    fakePool.execute(
        new Runnable() {
          @Override
          public void run() {
            Thread.currentThread().interrupt();
          }
        });
    // Run a task that expects that it is not interrupted while it is running.
    e.execute(
        new Runnable() {
          @Override
          public void run() {
            assertThat(Thread.currentThread().isInterrupted()).isFalse();
          }
        });

    // Run these together.
    fakePool.runAll();

    // Check that this thread has been marked as interrupted again now that the thread has been
    // returned by SequentialExecutor. Clear the bit while checking so that the test doesn't hose
    // JUnit or some other test case.
    assertThat(Thread.interrupted()).isTrue();
  }

  public void testInterrupt_doesNotInterruptSubsequentTask() throws Exception {
    // Run a task that interrupts its thread (i.e. this thread).
    e.execute(
        new Runnable() {
          @Override
          public void run() {
            Thread.currentThread().interrupt();
          }
        });
    // Run a task that expects that it is not interrupted while it is running.
    e.execute(
        new Runnable() {
          @Override
          public void run() {
            assertThat(Thread.currentThread().isInterrupted()).isFalse();
          }
        });

    // Run those tasks together.
    fakePool.runAll();

    // Check that the interruption of a SequentialExecutor's task is restored to the thread once
    // it is yielded. Clear the bit while checking so that the test doesn't hose JUnit or some other
    // test case.
    assertThat(Thread.interrupted()).isTrue();
  }

  public void testInterrupt_doesNotStopExecution() {

    final AtomicInteger numCalls = new AtomicInteger();

    Runnable runMe =
        new Runnable() {
          @Override
          public void run() {
            numCalls.incrementAndGet();
          }
        };

    Thread.currentThread().interrupt();

    e.execute(runMe);
    e.execute(runMe);
    fakePool.runAll();

    assertEquals(2, numCalls.get());

    assertTrue(Thread.interrupted());
  }

  public void testDelegateRejection() {
    final AtomicInteger numCalls = new AtomicInteger();
    final AtomicBoolean reject = new AtomicBoolean(true);
    final SequentialExecutor executor =
        new SequentialExecutor(
            new Executor() {
              @Override
              public void execute(Runnable r) {
                if (reject.get()) {
                  throw new RejectedExecutionException();
                }
                r.run();
              }
            });
    Runnable task =
        new Runnable() {
          @Override
          public void run() {
            numCalls.incrementAndGet();
          }
        };
    try {
      executor.execute(task);
      fail();
    } catch (RejectedExecutionException expected) {
    }
    assertEquals(0, numCalls.get());
    reject.set(false);
    executor.execute(task);
    assertEquals(1, numCalls.get());
  }

  /*
   * Under Android, MyError propagates up and fails the test?
   *
   * TODO(b/218700094): Does this matter to prod users, or is it just a feature of our testing
   * environment? If the latter, maybe write a custom Executor that avoids failing the test when it
   * sees an Error?
   */
  @AndroidIncompatible
  public void testTaskThrowsError() throws Exception {
    class MyError extends Error {}
    final CyclicBarrier barrier = new CyclicBarrier(2);
    // we need to make sure the error gets thrown on a different thread.
    ExecutorService service = Executors.newSingleThreadExecutor();
    try {
      final SequentialExecutor executor = new SequentialExecutor(service);
      Runnable errorTask =
          new Runnable() {
            @Override
            public void run() {
              throw new MyError();
            }
          };
      Runnable barrierTask =
          new Runnable() {
            @Override
            public void run() {
              try {
                barrier.await();
              } catch (Exception e) {
                throw new RuntimeException(e);
              }
            }
          };
      executor.execute(errorTask);
      service.execute(barrierTask); // submit directly to the service
      // the barrier task runs after the error task so we know that the error has been observed by
      // SequentialExecutor by the time the barrier is satisfied
      barrier.await(1, TimeUnit.SECONDS);
      executor.execute(barrierTask);
      // timeout means the second task wasn't even tried
      barrier.await(1, TimeUnit.SECONDS);
    } finally {
      service.shutdown();
    }
  }

  public void testRejectedExecutionThrownWithMultipleCalls() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final SettableFuture<?> future = SettableFuture.create();
    final Executor delegate =
        new Executor() {
          @Override
          public void execute(Runnable task) {
            if (future.set(null)) {
              awaitUninterruptibly(latch);
            }
            throw new RejectedExecutionException();
          }
        };
    final SequentialExecutor executor = new SequentialExecutor(delegate);
    final ExecutorService blocked = Executors.newCachedThreadPool();
    Future<?> first =
        blocked.submit(
            new Runnable() {
              @Override
              public void run() {
                executor.execute(Runnables.doNothing());
              }
            });
    future.get(10, TimeUnit.SECONDS);
    try {
      executor.execute(Runnables.doNothing());
      fail();
    } catch (RejectedExecutionException expected) {
    }
    latch.countDown();
    try {
      first.get(10, TimeUnit.SECONDS);
      fail();
    } catch (ExecutionException expected) {
      assertThat(expected).hasCauseThat().isInstanceOf(RejectedExecutionException.class);
    }
  }

  public void testToString() {
    final Runnable[] currentTask = new Runnable[1];
    final Executor delegate =
        new Executor() {
          @Override
          public void execute(Runnable task) {
            currentTask[0] = task;
            task.run();
            currentTask[0] = null;
          }

          @Override
          public String toString() {
            return "theDelegate";
          }
        };
    Executor sequential1 = newSequentialExecutor(delegate);
    Executor sequential2 = newSequentialExecutor(delegate);
    assertThat(sequential1.toString()).contains("theDelegate");
    assertThat(sequential1.toString()).isNotEqualTo(sequential2.toString());
    final String[] whileRunningToString = new String[1];
    sequential1.execute(
        new Runnable() {
          @Override
          public void run() {
            whileRunningToString[0] = "" + currentTask[0];
          }

          @Override
          public String toString() {
            return "my runnable's toString";
          }
        });
    assertThat(whileRunningToString[0]).contains("my runnable's toString");
  }
}