aboutsummaryrefslogtreecommitdiff
path: root/guava-tests/test/com/google/common/util/concurrent/UninterruptibleFutureTest.java
blob: f857c6edf1845797bfeeb92e729c8b7d6322a5ba (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
/*
 * Copyright (C) 2009 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.util.concurrent.InterruptionUtil.repeatedlyInterruptTestThread;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertThrows;

import com.google.common.testing.TearDown;
import com.google.common.testing.TearDownStack;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;

// TODO(cpovirk): Should this be merged into UninterruptiblesTest?
/**
 * Unit test for {@link Uninterruptibles#getUninterruptibly}
 *
 * @author Kevin Bourrillion
 * @author Chris Povirk
 */
public class UninterruptibleFutureTest extends TestCase {
  private SleepingRunnable sleeper;
  private Future<Boolean> delayedFuture;

  private final TearDownStack tearDownStack = new TearDownStack();

  @Override
  protected void setUp() {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    tearDownStack.addTearDown(
        new TearDown() {
          @Override
          public void tearDown() {
            executor.shutdownNow();
          }
        });
    sleeper = new SleepingRunnable(1000);
    delayedFuture = executor.submit(sleeper, true);

    tearDownStack.addTearDown(
        new TearDown() {
          @Override
          public void tearDown() {
            Thread.interrupted();
          }
        });
  }

  @Override
  protected void tearDown() {
    tearDownStack.runTearDown();
  }

  /**
   * This first test doesn't test anything in Uninterruptibles, just demonstrates some normal
   * behavior of futures so that you can contrast the next test with it.
   */
  public void testRegularFutureInterrupted() throws ExecutionException {

    /*
     * Here's the order of events that we want.
     *
     * 1. The client thread begins to block on a get() call to a future.
     * 2. The client thread is interrupted sometime before the result would be
     *   available.
     * 3. We expect the client's get() to throw an InterruptedException.
     * 4. We expect the client thread's interrupt state to be false.
     * 5. The client thread again makes a blocking call to get().
     * 6. Now the result becomes available.
     * 7. We expect get() to return this result.
     * 8. We expect the test thread's interrupt state to be false.
     */
    InterruptionUtil.requestInterruptIn(200, TimeUnit.MILLISECONDS);

    assertFalse(Thread.interrupted());
    try {
      delayedFuture.get(20000, TimeUnit.MILLISECONDS);
      fail("expected to be interrupted");
    } catch (InterruptedException expected) {
    } catch (TimeoutException e) {
      throw new RuntimeException(e);
    }

    // we were interrupted, but it's been cleared now
    assertFalse(Thread.interrupted());

    assertFalse(sleeper.completed);
    try {
      assertTrue(delayedFuture.get());
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    assertTrue(sleeper.completed);
  }

  public void testMakeUninterruptible_timeoutPreservedThroughInterruption()
      throws ExecutionException {

    repeatedlyInterruptTestThread(100, tearDownStack);

    assertThrows(
        TimeoutException.class,
        () -> getUninterruptibly(delayedFuture, 500, TimeUnit.MILLISECONDS));
    assertTrue(Thread.interrupted()); // clears the interrupt state, too

    assertFalse(sleeper.completed);
    assertTrue(getUninterruptibly(delayedFuture));

    assertTrue(Thread.interrupted()); // clears the interrupt state, too
    assertTrue(sleeper.completed);
  }

  private static class SleepingRunnable implements Runnable {
    final int millis;
    volatile boolean completed;

    public SleepingRunnable(int millis) {
      this.millis = millis;
    }

    @Override
    public void run() {
      try {
        Thread.sleep(millis);
      } catch (InterruptedException wontHappen) {
        throw new AssertionError();
      }
      completed = true;
    }
  }

  public void testMakeUninterruptible_untimed_uninterrupted() throws Exception {
    runUntimedInterruptsTest(0);
  }

  public void testMakeUninterruptible_untimed_interrupted() throws Exception {
    runUntimedInterruptsTest(1);
  }

  public void testMakeUninterruptible_untimed_multiplyInterrupted() throws Exception {
    runUntimedInterruptsTest(38);
  }

  public void testMakeUninterruptible_timed_uninterrupted() throws Exception {
    runTimedInterruptsTest(0);
  }

  public void testMakeUninterruptible_timed_interrupted() throws Exception {
    runTimedInterruptsTest(1);
  }

  public void testMakeUninterruptible_timed_multiplyInterrupted() throws Exception {
    runTimedInterruptsTest(38);
  }

  private static void runUntimedInterruptsTest(int times)
      throws InterruptedException, ExecutionException, TimeoutException {
    SettableFuture<String> future = SettableFuture.create();
    FutureTask<Boolean> interruptReporter = untimedInterruptReporter(future, false);

    runNInterruptsTest(times, future, interruptReporter);
  }

  private static void runTimedInterruptsTest(int times)
      throws InterruptedException, ExecutionException, TimeoutException {
    SettableFuture<String> future = SettableFuture.create();
    FutureTask<Boolean> interruptReporter = timedInterruptReporter(future);

    runNInterruptsTest(times, future, interruptReporter);
  }

  private static void runNInterruptsTest(
      int times, SettableFuture<String> future, FutureTask<Boolean> interruptReporter)
      throws InterruptedException, ExecutionException, TimeoutException {
    Thread waitingThread = new Thread(interruptReporter);
    waitingThread.start();
    for (int i = 0; i < times; i++) {
      waitingThread.interrupt();
    }

    future.set(RESULT);

    assertEquals(times > 0, (boolean) interruptReporter.get(20, SECONDS));
  }

  /**
   * Confirms that the test code triggers {@link InterruptedException} in a standard {@link Future}.
   */
  public void testMakeUninterruptible_plainFutureSanityCheck() throws Exception {
    SettableFuture<String> future = SettableFuture.create();
    FutureTask<Boolean> wasInterrupted = untimedInterruptReporter(future, true);

    Thread waitingThread = new Thread(wasInterrupted);
    waitingThread.start();
    waitingThread.interrupt();
    ExecutionException expected =
        assertThrows(ExecutionException.class, () -> wasInterrupted.get());
    assertTrue(expected.getCause().toString(), expected.getCause() instanceof InterruptedException);
  }

  public void testMakeUninterruptible_timedGetZeroTimeoutAttempted()
      throws TimeoutException, ExecutionException {
    SettableFuture<String> future = SettableFuture.create();
    future.set(RESULT);
    /*
     * getUninterruptibly should call the timed get method once with a
     * wait of 0 seconds (and it should succeed, since the result is already
     * available).
     */
    assertEquals(RESULT, getUninterruptibly(future, 0, SECONDS));
  }

  public void testMakeUninterruptible_timedGetNegativeTimeoutAttempted()
      throws TimeoutException, ExecutionException {
    SettableFuture<String> future = SettableFuture.create();
    future.set(RESULT);
    /*
     * The getUninterruptibly should call the timed get method once with a
     * wait of -1 seconds (and it should succeed, since the result is already
     * available).
     */
    assertEquals(RESULT, getUninterruptibly(future, -1, SECONDS));
  }

  private static FutureTask<Boolean> untimedInterruptReporter(
      final Future<?> future, final boolean allowInterruption) {
    return new FutureTask<>(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            Object actual;
            if (allowInterruption) {
              actual = future.get();
            } else {
              actual = getUninterruptibly(future);
            }
            assertEquals(RESULT, actual);
            return Thread.interrupted();
          }
        });
  }

  private static FutureTask<Boolean> timedInterruptReporter(final Future<?> future) {
    return new FutureTask<>(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            assertEquals(RESULT, getUninterruptibly(future, 10, MINUTES));
            return Thread.interrupted();
          }
        });
  }

  private static final String RESULT = "result";
}