aboutsummaryrefslogtreecommitdiff
path: root/guava-tests/test/com/google/common/util/concurrent/TestThread.java
blob: ef3b27410d40e9a890999cacf2774f28d9cbf755 (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
/*
 * Copyright (C) 2010 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.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertSame;

import com.google.common.testing.TearDown;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A helper for concurrency testing. One or more {@code TestThread} instances are instantiated in a
 * test with reference to the same "lock-like object", and then their interactions with that object
 * are choreographed via the various methods on this class.
 *
 * <p>A "lock-like object" is really any object that may be used for concurrency control. If the
 * {@link #callAndAssertBlocks} method is ever called in a test, the lock-like object must have a
 * method equivalent to {@link java.util.concurrent.locks.ReentrantLock#hasQueuedThread(Thread)}. If
 * the {@link #callAndAssertWaits} method is ever called in a test, the lock-like object must have a
 * method equivalent to {@link
 * java.util.concurrent.locks.ReentrantLock#hasWaiters(java.util.concurrent.locks.Condition)},
 * except that the method parameter must accept whatever condition-like object is passed into {@code
 * callAndAssertWaits} by the test.
 *
 * @param <L> the type of the lock-like object to be used
 * @author Justin T. Sampson
 */
public final class TestThread<L> extends Thread implements TearDown {

  private static final long DUE_DILIGENCE_MILLIS = 100;
  private static final long TIMEOUT_MILLIS = 5000;

  private final L lockLikeObject;

  private final SynchronousQueue<Request> requestQueue = new SynchronousQueue<>();
  private final SynchronousQueue<Response> responseQueue = new SynchronousQueue<>();

  private @Nullable Throwable uncaughtThrowable = null;

  public TestThread(L lockLikeObject, String threadName) {
    super(threadName);
    this.lockLikeObject = checkNotNull(lockLikeObject);
    start();
  }

  // Thread.stop() is okay because all threads started by a test are dying at the end of the test,
  // so there is no object state put at risk by stopping the threads abruptly. In some cases a test
  // may put a thread into an uninterruptible operation intentionally, so there is no other way to
  // clean up these threads.
  @SuppressWarnings("deprecation")
  @Override
  public void tearDown() throws Exception {
    stop();
    join();

    if (uncaughtThrowable != null) {
      throw (AssertionFailedError)
          new AssertionFailedError("Uncaught throwable in " + getName())
              .initCause(uncaughtThrowable);
    }
  }

  /**
   * Causes this thread to call the named void method, and asserts that the call returns normally.
   */
  public void callAndAssertReturns(String methodName, Object... arguments) throws Exception {
    checkNotNull(methodName);
    checkNotNull(arguments);
    sendRequest(methodName, arguments);
    assertSame(null, getResponse(methodName).getResult());
  }

  /**
   * Causes this thread to call the named method, and asserts that the call returns the expected
   * boolean value.
   */
  public void callAndAssertReturns(boolean expected, String methodName, Object... arguments)
      throws Exception {
    checkNotNull(methodName);
    checkNotNull(arguments);
    sendRequest(methodName, arguments);
    assertEquals(expected, getResponse(methodName).getResult());
  }

  /**
   * Causes this thread to call the named method, and asserts that the call returns the expected int
   * value.
   */
  public void callAndAssertReturns(int expected, String methodName, Object... arguments)
      throws Exception {
    checkNotNull(methodName);
    checkNotNull(arguments);
    sendRequest(methodName, arguments);
    assertEquals(expected, getResponse(methodName).getResult());
  }

  /**
   * Causes this thread to call the named method, and asserts that the call throws the expected type
   * of throwable.
   */
  public void callAndAssertThrows(
      Class<? extends Throwable> expected, String methodName, Object... arguments)
      throws Exception {
    checkNotNull(expected);
    checkNotNull(methodName);
    checkNotNull(arguments);
    sendRequest(methodName, arguments);
    assertEquals(expected, getResponse(methodName).getThrowable().getClass());
  }

  /**
   * Causes this thread to call the named method, and asserts that this thread becomes blocked on
   * the lock-like object. The lock-like object must have a method equivalent to {@link
   * java.util.concurrent.locks.ReentrantLock#hasQueuedThread(Thread)}.
   */
  public void callAndAssertBlocks(String methodName, Object... arguments) throws Exception {
    checkNotNull(methodName);
    checkNotNull(arguments);
    assertEquals(false, invokeMethod("hasQueuedThread", this));
    sendRequest(methodName, arguments);
    Thread.sleep(DUE_DILIGENCE_MILLIS);
    assertEquals(true, invokeMethod("hasQueuedThread", this));
    assertNull(responseQueue.poll());
  }

  /**
   * Causes this thread to call the named method, and asserts that this thread thereby waits on the
   * given condition-like object. The lock-like object must have a method equivalent to {@link
   * java.util.concurrent.locks.ReentrantLock#hasWaiters(java.util.concurrent.locks.Condition)},
   * except that the method parameter must accept whatever condition-like object is passed into this
   * method.
   */
  public void callAndAssertWaits(String methodName, Object conditionLikeObject) throws Exception {
    checkNotNull(methodName);
    checkNotNull(conditionLikeObject);
    // TODO: Restore the following line when Monitor.hasWaiters() no longer acquires the lock.
    // assertEquals(false, invokeMethod("hasWaiters", conditionLikeObject));
    sendRequest(methodName, conditionLikeObject);
    Thread.sleep(DUE_DILIGENCE_MILLIS);
    assertEquals(true, invokeMethod("hasWaiters", conditionLikeObject));
    assertNull(responseQueue.poll());
  }

  /**
   * Asserts that a prior call that had caused this thread to block or wait has since returned
   * normally.
   */
  public void assertPriorCallReturns(@Nullable String methodName) throws Exception {
    assertEquals(null, getResponse(methodName).getResult());
  }

  /**
   * Asserts that a prior call that had caused this thread to block or wait has since returned the
   * expected boolean value.
   */
  public void assertPriorCallReturns(boolean expected, @Nullable String methodName)
      throws Exception {
    assertEquals(expected, getResponse(methodName).getResult());
  }

  /**
   * Sends the given method call to this thread.
   *
   * @throws TimeoutException if this thread does not accept the request within a reasonable amount
   *     of time
   */
  private void sendRequest(String methodName, Object... arguments) throws Exception {
    if (!requestQueue.offer(
        new Request(methodName, arguments), TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
      throw new TimeoutException();
    }
  }

  /**
   * Receives a response from this thread.
   *
   * @throws TimeoutException if this thread does not offer a response within a reasonable amount of
   *     time
   * @throws AssertionFailedError if the given method name does not match the name of the method
   *     this thread has called most recently
   */
  private Response getResponse(String methodName) throws Exception {
    Response response = responseQueue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    if (response == null) {
      throw new TimeoutException();
    }
    assertEquals(methodName, response.methodName);
    return response;
  }

  private Object invokeMethod(String methodName, Object... arguments) throws Exception {
    return getMethod(methodName, arguments).invoke(lockLikeObject, arguments);
  }

  private Method getMethod(String methodName, Object... arguments) throws Exception {
    METHODS:
    for (Method method : lockLikeObject.getClass().getMethods()) {
      Class<?>[] parameterTypes = method.getParameterTypes();
      if (method.getName().equals(methodName) && (parameterTypes.length == arguments.length)) {
        for (int i = 0; i < arguments.length; i++) {
          if (!parameterTypes[i].isAssignableFrom(arguments[i].getClass())) {
            continue METHODS;
          }
        }
        return method;
      }
    }
    throw new NoSuchMethodError(methodName);
  }

  @Override
  public void run() {
    assertSame(this, Thread.currentThread());
    try {
      while (true) {
        Request request = requestQueue.take();
        Object result;
        try {
          result = invokeMethod(request.methodName, request.arguments);
        } catch (ThreadDeath death) {
          return;
        } catch (InvocationTargetException exception) {
          responseQueue.put(new Response(request.methodName, null, exception.getTargetException()));
          continue;
        } catch (Throwable throwable) {
          responseQueue.put(new Response(request.methodName, null, throwable));
          continue;
        }
        responseQueue.put(new Response(request.methodName, result, null));
      }
    } catch (ThreadDeath death) {
      return;
    } catch (InterruptedException ignored) {
      // SynchronousQueue sometimes throws InterruptedException while the threads are stopping.
    } catch (Throwable uncaught) {
      this.uncaughtThrowable = uncaught;
    }
  }

  private static class Request {
    final String methodName;
    final Object[] arguments;

    Request(String methodName, Object[] arguments) {
      this.methodName = checkNotNull(methodName);
      this.arguments = checkNotNull(arguments);
    }
  }

  private static class Response {
    final String methodName;
    final Object result;
    final Throwable throwable;

    Response(String methodName, @Nullable Object result, @Nullable Throwable throwable) {
      this.methodName = methodName;
      this.result = result;
      this.throwable = throwable;
    }

    Object getResult() {
      if (throwable != null) {
        throw (AssertionFailedError) new AssertionFailedError().initCause(throwable);
      }
      return result;
    }

    Throwable getThrowable() {
      assertNotNull(throwable);
      return throwable;
    }
  }
}