aboutsummaryrefslogtreecommitdiffstats
path: root/guava-tests/test/com/google/common/util/concurrent
diff options
context:
space:
mode:
Diffstat (limited to 'guava-tests/test/com/google/common/util/concurrent')
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java85
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java32
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java218
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java95
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java550
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java1
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AtomicLongMapTest.java25
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java581
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java64
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingBlockingQueueTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingCheckedFutureTest.java90
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingExecutorServiceTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingFutureTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingListenableFutureTest.java44
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingListeningExecutorServiceTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java74
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTesterTest.java53
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ForwardingServiceTest.java28
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/FuturesTest.java693
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java20
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java11
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java9
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java240
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java27
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java363
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java2
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/StripedTest.java165
-rw-r--r--guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java23
30 files changed, 444 insertions, 3165 deletions
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java
index 9b14c7d..d7fd91e 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java
@@ -17,8 +17,6 @@
package com.google.common.util.concurrent;
import com.google.common.base.Throwables;
-import com.google.common.testing.TearDown;
-import com.google.common.testing.TearDownStack;
import junit.framework.TestCase;
@@ -26,8 +24,6 @@ import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.CountDownLatch;
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.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -39,7 +35,6 @@ import java.util.concurrent.TimeoutException;
*/
public class AbstractExecutionThreadServiceTest extends TestCase {
- private final TearDownStack tearDownStack = new TearDownStack(true);
private final CountDownLatch enterRun = new CountDownLatch(1);
private final CountDownLatch exitRun = new CountDownLatch(1);
@@ -59,10 +54,6 @@ public class AbstractExecutionThreadServiceTest extends TestCase {
}
};
- @Override protected final void tearDown() {
- tearDownStack.runTearDown();
- }
-
public void testServiceStartStop() throws Exception {
WaitOnRunService service = new WaitOnRunService();
assertFalse(service.startUpCalled);
@@ -308,80 +299,4 @@ public class AbstractExecutionThreadServiceTest extends TestCase {
}
}
- public void testStopWhileStarting_runNotCalled() throws Exception {
- final CountDownLatch started = new CountDownLatch(1);
- FakeService service = new FakeService() {
- @Override protected void startUp() throws Exception {
- super.startUp();
- started.await();
- }
- };
- service.start();
- ListenableFuture<Service.State> stopped = service.stop();
- started.countDown();
- assertEquals(Service.State.TERMINATED, stopped.get());
- assertEquals(Service.State.TERMINATED, service.state());
- assertEquals(1, service.startupCalled);
- assertEquals(0, service.runCalled);
- assertEquals(1, service.shutdownCalled);
- }
-
- public void testStop_noStart() {
- FakeService service = new FakeService();
- assertEquals(Service.State.TERMINATED, service.stopAndWait());
- assertEquals(Service.State.TERMINATED, service.state());
- assertEquals(0, service.startupCalled);
- assertEquals(0, service.runCalled);
- assertEquals(0, service.shutdownCalled);
- }
-
- public void testDefaultService() {
- AbstractExecutionThreadService service = new AbstractExecutionThreadService() {
- @Override protected void run() throws Exception {}
- };
- assertEquals(Service.State.RUNNING, service.startAndWait());
- assertEquals(Service.State.TERMINATED, service.stopAndWait());
- }
-
- private class FakeService extends AbstractExecutionThreadService implements TearDown {
-
- private final ExecutorService executor = Executors.newSingleThreadExecutor();
-
- FakeService() {
- tearDownStack.addTearDown(this);
- }
-
- volatile int startupCalled = 0;
- volatile int shutdownCalled = 0;
- volatile int runCalled = 0;
-
- @Override protected void startUp() throws Exception {
- assertEquals(0, startupCalled);
- assertEquals(0, runCalled);
- assertEquals(0, shutdownCalled);
- startupCalled++;
- }
-
- @Override protected void run() throws Exception {
- assertEquals(1, startupCalled);
- assertEquals(0, runCalled);
- assertEquals(0, shutdownCalled);
- runCalled++;
- }
-
- @Override protected void shutDown() throws Exception {
- assertEquals(1, startupCalled);
- assertEquals(0, shutdownCalled);
- assertEquals(Service.State.STOPPING, state());
- shutdownCalled++;
- }
-
- @Override protected Executor executor() {
- return executor;
- }
-
- @Override public void tearDown() throws Exception {
- executor.shutdown();
- }
- }
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
index 4024a8e..a7dd412 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java
@@ -16,12 +16,11 @@
package com.google.common.util.concurrent;
-import static org.truth0.Truth.ASSERT;
+import static org.junit.contrib.truth.Truth.ASSERT;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
-import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -64,37 +63,23 @@ public class AbstractFutureTest extends TestCase {
checkStackTrace(ee2);
}
- public void testCancel_notDoneNoInterrupt() throws Exception {
+ public void testCancel_notDoneNoInterrupt() {
InterruptibleFuture future = new InterruptibleFuture();
assertTrue(future.cancel(false));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
- assertFalse(future.wasInterrupted());
- assertFalse(future.interruptTaskWasCalled);
- try {
- future.get();
- fail("Expected CancellationException");
- } catch (CancellationException e) {
- assertNotNull(e.getCause());
- }
+ assertFalse(future.wasInterrupted);
}
- public void testCancel_notDoneInterrupt() throws Exception {
+ public void testCancel_notDoneInterrupt() {
InterruptibleFuture future = new InterruptibleFuture();
assertTrue(future.cancel(true));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
- assertTrue(future.wasInterrupted());
- assertTrue(future.interruptTaskWasCalled);
- try {
- future.get();
- fail("Expected CancellationException");
- } catch (CancellationException e) {
- assertNotNull(e.getCause());
- }
+ assertTrue(future.wasInterrupted);
}
- public void testCancel_done() throws Exception {
+ public void testCancel_done() {
AbstractFuture<String> future = new AbstractFuture<String>() {
{
set("foo");
@@ -192,11 +177,10 @@ public class AbstractFutureTest extends TestCase {
private static final class InterruptibleFuture
extends AbstractFuture<String> {
- boolean interruptTaskWasCalled;
+ boolean wasInterrupted;
@Override protected void interruptTask() {
- assertFalse(interruptTaskWasCalled);
- interruptTaskWasCalled = true;
+ wasInterrupted = true;
}
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
index 2939661..8131a37 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java
@@ -16,200 +16,112 @@
package com.google.common.util.concurrent;
-import static org.truth0.Truth.ASSERT;
-
-import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Service.State;
import junit.framework.TestCase;
-import java.util.List;
+import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
- * Tests for {@link AbstractIdleService}.
+ * Unit test for {@link AbstractIdleService}.
*
* @author Chris Nokleberg
- * @author Ben Yu
*/
public class AbstractIdleServiceTest extends TestCase {
-
- // Functional tests using real thread. We only verify publicly visible state.
- // Interaction assertions are done by the single-threaded unit tests.
-
- public static class FunctionalTest extends TestCase {
-
- private static class DefaultService extends AbstractIdleService {
- @Override protected void startUp() throws Exception {}
- @Override protected void shutDown() throws Exception {}
+ private Thread executorThread;
+ private Throwable thrownByExecutorThread;
+ private final Executor executor = new Executor() {
+ @Override
+ public void execute(Runnable command) {
+ executorThread = new Thread(command);
+ executorThread.setUncaughtExceptionHandler(
+ new UncaughtExceptionHandler() {
+ @Override
+ public void uncaughtException(Thread thread, Throwable e) {
+ thrownByExecutorThread = e;
+ }
+ });
+ executorThread.start();
}
+ };
- public void testServiceStartStop() throws Exception {
- AbstractIdleService service = new DefaultService();
- assertEquals(Service.State.RUNNING, service.startAndWait());
- assertEquals(Service.State.RUNNING, service.state());
- assertEquals(Service.State.TERMINATED, service.stopAndWait());
- assertEquals(Service.State.TERMINATED, service.state());
- }
-
- public void testStart_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service = new DefaultService() {
- @Override protected void startUp() throws Exception {
- throw exception;
- }
- };
- try {
- service.startAndWait();
- fail();
- } catch (RuntimeException e) {
- assertSame(exception, e.getCause());
- }
- assertEquals(Service.State.FAILED, service.state());
- }
+ public void testServiceStartStop() throws Exception {
+ NullService service = new NullService();
+ assertFalse(service.startUpCalled);
- public void testStop_failed() throws Exception {
- final Exception exception = new Exception("deliberate");
- AbstractIdleService service = new DefaultService() {
- @Override protected void shutDown() throws Exception {
- throw exception;
- }
- };
- service.startAndWait();
- try {
- service.stopAndWait();
- fail();
- } catch (RuntimeException e) {
- assertSame(exception, e.getCause());
- }
- assertEquals(Service.State.FAILED, service.state());
- }
- }
-
- public void testStart() {
- TestService service = new TestService();
- assertEquals(0, service.startUpCalled);
- service.startAndWait();
- assertEquals(1, service.startUpCalled);
+ service.start().get();
+ assertTrue(service.startUpCalled);
assertEquals(Service.State.RUNNING, service.state());
- ASSERT.that(service.transitionStates).has().allOf(Service.State.STARTING).inOrder();
- }
-
- public void testStart_failed() {
- final Exception exception = new Exception("deliberate");
- TestService service = new TestService() {
- @Override protected void startUp() throws Exception {
- super.startUp();
- throw exception;
- }
- };
- assertEquals(0, service.startUpCalled);
- try {
- service.startAndWait();
- fail();
- } catch (RuntimeException e) {
- assertSame(exception, e.getCause());
- }
- assertEquals(1, service.startUpCalled);
- assertEquals(Service.State.FAILED, service.state());
- ASSERT.that(service.transitionStates).has().allOf(Service.State.STARTING).inOrder();
- }
- public void testStop_withoutStart() {
- TestService service = new TestService();
- service.stopAndWait();
- assertEquals(0, service.startUpCalled);
- assertEquals(0, service.shutDownCalled);
+ service.stop().get();
+ assertTrue(service.shutDownCalled);
assertEquals(Service.State.TERMINATED, service.state());
- ASSERT.that(service.transitionStates).isEmpty();
+ executorThread.join();
+ assertNull(thrownByExecutorThread);
}
- public void testStop_afterStart() {
- TestService service = new TestService();
- service.startAndWait();
- assertEquals(1, service.startUpCalled);
- assertEquals(0, service.shutDownCalled);
- service.stopAndWait();
- assertEquals(1, service.startUpCalled);
- assertEquals(1, service.shutDownCalled);
- assertEquals(Service.State.TERMINATED, service.state());
- ASSERT.that(service.transitionStates)
- .has().allOf(Service.State.STARTING, Service.State.STOPPING).inOrder();
- }
-
- public void testStop_failed() {
- final Exception exception = new Exception("deliberate");
- TestService service = new TestService() {
- @Override protected void shutDown() throws Exception {
- super.shutDown();
- throw exception;
- }
- };
- service.startAndWait();
- assertEquals(1, service.startUpCalled);
- assertEquals(0, service.shutDownCalled);
- try {
- service.stopAndWait();
- fail();
- } catch (RuntimeException e) {
- assertSame(exception, e.getCause());
- }
- assertEquals(1, service.startUpCalled);
- assertEquals(1, service.shutDownCalled);
- assertEquals(Service.State.FAILED, service.state());
- ASSERT.that(service.transitionStates)
- .has().allOf(Service.State.STARTING, Service.State.STOPPING).inOrder();
- }
-
- public void testServiceToString() {
- AbstractIdleService service = new TestService();
- assertEquals("TestService [NEW]", service.toString());
- service.startAndWait();
- assertEquals("TestService [RUNNING]", service.toString());
- service.stopAndWait();
- assertEquals("TestService [TERMINATED]", service.toString());
+ public void testServiceToString() throws Exception {
+ NullService service = new NullService();
+ assertEquals("NullService [" + Service.State.NEW + "]", service.toString());
+ service.start().get();
+ assertEquals("NullService [" + Service.State.RUNNING + "]", service.toString());
+ service.stop().get();
+ assertEquals("NullService [" + Service.State.TERMINATED + "]", service.toString());
}
public void testTimeout() throws Exception {
// Create a service whose executor will never run its commands
- Service service = new TestService() {
- @Override protected Executor executor() {
+ Service service = new NullService() {
+ @Override protected Executor executor(Service.State state) {
return new Executor() {
- @Override public void execute(Runnable command) {}
+ @Override public void execute(Runnable command) {
+ }
};
}
};
+
try {
service.start().get(1, TimeUnit.MILLISECONDS);
fail("Expected timeout");
} catch (TimeoutException e) {
- ASSERT.that(e.getMessage()).contains(Service.State.STARTING.toString());
+ assertTrue(e.getMessage().contains(State.STARTING.toString()));
}
}
- private static class TestService extends AbstractIdleService {
- int startUpCalled = 0;
- int shutDownCalled = 0;
- final List<State> transitionStates = Lists.newArrayList();
+ private class NullService extends AbstractIdleService {
+ boolean startUpCalled = false;
+ boolean shutDownCalled = false;
+ State expectedShutdownState = State.STOPPING;
- @Override protected void startUp() throws Exception {
- assertEquals(0, startUpCalled);
- assertEquals(0, shutDownCalled);
- startUpCalled++;
+ @Override protected void startUp() {
+ assertFalse(startUpCalled);
+ assertFalse(shutDownCalled);
+ startUpCalled = true;
assertEquals(State.STARTING, state());
}
- @Override protected void shutDown() throws Exception {
- assertEquals(1, startUpCalled);
- assertEquals(0, shutDownCalled);
- shutDownCalled++;
- assertEquals(State.STOPPING, state());
+ @Override protected void shutDown() {
+ assertTrue(startUpCalled);
+ assertFalse(shutDownCalled);
+ shutDownCalled = true;
+ assertEquals(expectedShutdownState, state());
}
- @Override protected Executor executor() {
- transitionStates.add(state());
- return MoreExecutors.sameThreadExecutor();
+ @Override protected Executor executor(Service.State state) {
+ switch (state) {
+ case STARTING:
+ assertFalse(startUpCalled);
+ return executor;
+ case STOPPING:
+ assertTrue(startUpCalled);
+ assertFalse(shutDownCalled);
+ return executor;
+ default:
+ throw new IllegalStateException("unexpected state " + state);
+ }
}
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
index 95f9fa8..c839e44 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java
@@ -21,7 +21,6 @@ import com.google.common.util.concurrent.Service.State;
import junit.framework.TestCase;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
@@ -29,6 +28,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
+
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -65,7 +65,9 @@ public class AbstractScheduledServiceTest extends TestCase {
}
private class NullService extends AbstractScheduledService {
- @Override protected void runOneIteration() throws Exception {}
+ @Override protected void runOneIteration() throws Exception { }
+ @Override protected void startUp() throws Exception { }
+ @Override protected void shutDown() throws Exception { }
@Override protected Scheduler scheduler() { return configuration; }
@Override protected ScheduledExecutorService executor() { return executor; }
}
@@ -148,85 +150,6 @@ public class AbstractScheduledServiceTest extends TestCase {
assertEquals(1, service.numberOfTimesExecutorCalled.get());
}
- public void testDefaultExecutorIsShutdownWhenServiceIsStopped() throws Exception {
- final CountDownLatch terminationLatch = new CountDownLatch(1);
- AbstractScheduledService service = new AbstractScheduledService() {
- volatile ScheduledExecutorService executorService;
- @Override protected void runOneIteration() throws Exception {}
-
- @Override protected ScheduledExecutorService executor() {
- if (executorService == null) {
- executorService = super.executor();
- // Add a listener that will be executed after the listener that shuts down the executor.
- addListener(new Listener() {
- @Override public void starting() {}
- @Override public void running() {}
- @Override public void stopping(State from) {}
- @Override public void terminated(State from) {
- terminationLatch.countDown();
- }
- @Override public void failed(State from, Throwable failure) {}
- }, MoreExecutors.sameThreadExecutor());
- }
- return executorService;
- }
-
- @Override protected Scheduler scheduler() {
- return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.MILLISECONDS);
- }};
-
- service.start();
- assertFalse(service.executor().isShutdown());
- service.startAndWait();
- service.stop();
- terminationLatch.await();
- assertTrue(service.executor().isShutdown());
- assertTrue(service.executor().awaitTermination(100, TimeUnit.MILLISECONDS));
- }
-
- public void testDefaultExecutorIsShutdownWhenServiceFails() throws Exception {
- final CountDownLatch failureLatch = new CountDownLatch(1);
- AbstractScheduledService service = new AbstractScheduledService() {
- volatile ScheduledExecutorService executorService;
- @Override protected void runOneIteration() throws Exception {}
-
- @Override protected void startUp() throws Exception {
- throw new Exception("Failed");
- }
-
- @Override protected ScheduledExecutorService executor() {
- if (executorService == null) {
- executorService = super.executor();
- // Add a listener that will be executed after the listener that shuts down the executor.
- addListener(new Listener() {
- @Override public void starting() {}
- @Override public void running() {}
- @Override public void stopping(State from) {}
- @Override public void terminated(State from) {
- }
- @Override public void failed(State from, Throwable failure) {
- failureLatch.countDown();
- }
- }, MoreExecutors.sameThreadExecutor());
- }
- return executorService;
- }
-
- @Override protected Scheduler scheduler() {
- return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.MILLISECONDS);
- }};
-
- try {
- service.startAndWait();
- fail("Expected service to fail during startup");
- } catch (UncheckedExecutionException e) {
- // expected
- }
- failureLatch.await();
- assertTrue(service.executor().isShutdown());
- assertTrue(service.executor().awaitTermination(100, TimeUnit.MILLISECONDS));
- }
-
public void testSchedulerOnlyCalledOnce() throws Exception {
TestService service = new TestService();
service.startAndWait();
@@ -405,7 +328,7 @@ public class AbstractScheduledServiceTest extends TestCase {
public void testBig() throws Exception {
TestAbstractScheduledCustomService service = new TestAbstractScheduledCustomService() {
@Override protected Scheduler scheduler() {
- return new AbstractScheduledService.CustomScheduler() {
+ return new AbstractScheduledService.CustomScheduler(){
@Override
protected Schedule getNextSchedule() throws Exception {
// Explicitly yield to increase the probability of a pathological scheduling.
@@ -446,9 +369,9 @@ public class AbstractScheduledServiceTest extends TestCase {
return Executors.newScheduledThreadPool(10);
}
- @Override protected void startUp() throws Exception {}
+ @Override protected void startUp() throws Exception { }
- @Override protected void shutDown() throws Exception {}
+ @Override protected void shutDown() throws Exception { }
@Override protected Scheduler scheduler() {
return new CustomScheduler() {
@@ -492,6 +415,10 @@ public class AbstractScheduledServiceTest extends TestCase {
return Executors.newScheduledThreadPool(10);
}
+ @Override protected void startUp() throws Exception { }
+
+ @Override protected void shutDown() throws Exception { }
+
@Override protected Scheduler scheduler() {
return new CustomScheduler() {
@Override
diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java
index 99e2ffb..c4d4f8e 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java
@@ -19,21 +19,12 @@ package com.google.common.util.concurrent;
import static java.lang.Thread.currentThread;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Service.Listener;
-import com.google.common.util.concurrent.Service.State;
-
+import junit.framework.Assert;
import junit.framework.TestCase;
import java.lang.Thread.UncaughtExceptionHandler;
-import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import javax.annotation.concurrent.GuardedBy;
/**
* Unit test for {@link AbstractService}.
@@ -45,59 +36,43 @@ public class AbstractServiceTest extends TestCase {
private Thread executionThread;
private Throwable thrownByExecutionThread;
- public void testNoOpServiceStartStop() throws Exception {
+ public void testNoOpServiceStartStop() {
NoOpService service = new NoOpService();
- RecordingListener listener = RecordingListener.record(service);
-
- assertEquals(State.NEW, service.state());
+ Assert.assertEquals(Service.State.NEW, service.state());
assertFalse(service.isRunning());
assertFalse(service.running);
service.start();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
assertTrue(service.isRunning());
assertTrue(service.running);
service.stop();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
assertFalse(service.isRunning());
assertFalse(service.running);
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.TERMINATED),
- listener.getStateHistory());
}
public void testNoOpServiceStartAndWaitStopAndWait() throws Exception {
NoOpService service = new NoOpService();
service.start().get();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.stop().get();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
}
public void testNoOpServiceStartStopIdempotence() throws Exception {
NoOpService service = new NoOpService();
- RecordingListener listener = RecordingListener.record(service);
+
service.start();
service.start();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.stop();
service.stop();
- assertEquals(State.TERMINATED, service.state());
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.TERMINATED),
- listener.getStateHistory());
+ assertEquals(Service.State.TERMINATED, service.state());
}
public void testNoOpServiceStartStopIdempotenceAfterWait() throws Exception {
@@ -105,11 +80,11 @@ public class AbstractServiceTest extends TestCase {
service.start().get();
service.start();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.stop().get();
service.stop();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
}
public void testNoOpServiceStartStopIdempotenceDoubleWait() throws Exception {
@@ -117,11 +92,11 @@ public class AbstractServiceTest extends TestCase {
service.start().get();
service.start().get();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.stop().get();
service.stop().get();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
}
public void testNoOpServiceStartStopAndWaitUninterruptible()
@@ -131,10 +106,10 @@ public class AbstractServiceTest extends TestCase {
currentThread().interrupt();
try {
service.startAndWait();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.stopAndWait();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
assertTrue(currentThread().isInterrupted());
} finally {
@@ -158,125 +133,49 @@ public class AbstractServiceTest extends TestCase {
}
}
- public void testManualServiceStartStop() throws Exception {
+ public void testManualServiceStartStop() {
ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
service.start();
- assertEquals(State.STARTING, service.state());
+ assertEquals(Service.State.STARTING, service.state());
assertFalse(service.isRunning());
assertTrue(service.doStartCalled);
service.notifyStarted(); // usually this would be invoked by another thread
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
assertTrue(service.isRunning());
service.stop();
- assertEquals(State.STOPPING, service.state());
+ assertEquals(Service.State.STOPPING, service.state());
assertFalse(service.isRunning());
assertTrue(service.doStopCalled);
service.notifyStopped(); // usually this would be invoked by another thread
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
assertFalse(service.isRunning());
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.TERMINATED),
- listener.getStateHistory());
-
}
- public void testManualServiceNotifyStoppedWhileRunning() throws Exception {
+ public void testManualServiceStopWhileStarting() {
ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
service.start();
- service.notifyStarted();
- service.notifyStopped();
- assertEquals(State.TERMINATED, service.state());
- assertFalse(service.isRunning());
- assertFalse(service.doStopCalled);
-
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.TERMINATED),
- listener.getStateHistory());
- }
-
- public void testManualServiceStopWhileStarting() throws Exception {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
-
- service.start();
- assertEquals(State.STARTING, service.state());
+ assertEquals(Service.State.STARTING, service.state());
assertFalse(service.isRunning());
assertTrue(service.doStartCalled);
service.stop();
- assertEquals(State.STOPPING, service.state());
+ assertEquals(Service.State.STOPPING, service.state());
assertFalse(service.isRunning());
assertFalse(service.doStopCalled);
service.notifyStarted();
- assertEquals(State.STOPPING, service.state());
+ assertEquals(Service.State.STOPPING, service.state());
assertFalse(service.isRunning());
assertTrue(service.doStopCalled);
service.notifyStopped();
- assertEquals(State.TERMINATED, service.state());
- assertFalse(service.isRunning());
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.STOPPING,
- State.TERMINATED),
- listener.getStateHistory());
- }
-
- public void testManualServiceStopWhileNew() throws Exception {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
-
- service.stop();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
assertFalse(service.isRunning());
- assertFalse(service.doStartCalled);
- assertFalse(service.doStopCalled);
- assertEquals(ImmutableList.of(State.TERMINATED), listener.getStateHistory());
- }
-
- public void testManualServiceFailWhileStarting() throws Exception {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
- service.start();
- service.notifyFailed(EXCEPTION);
- assertEquals(ImmutableList.of(State.STARTING, State.FAILED), listener.getStateHistory());
- }
-
- public void testManualServiceFailWhileRunning() throws Exception {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
- service.start();
- service.notifyStarted();
- service.notifyFailed(EXCEPTION);
- assertEquals(ImmutableList.of(State.STARTING, State.RUNNING, State.FAILED),
- listener.getStateHistory());
- }
-
- public void testManualServiceFailWhileStopping() throws Exception {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener listener = RecordingListener.record(service);
- service.start();
- service.notifyStarted();
- service.stop();
- service.notifyFailed(EXCEPTION);
- assertEquals(ImmutableList.of(State.STARTING, State.RUNNING, State.STOPPING, State.FAILED),
- listener.getStateHistory());
}
public void testManualServiceUnrequestedStop() {
@@ -285,12 +184,12 @@ public class AbstractServiceTest extends TestCase {
service.start();
service.notifyStarted();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
assertTrue(service.isRunning());
assertFalse(service.doStopCalled);
service.notifyStopped();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
assertFalse(service.isRunning());
assertFalse(service.doStopCalled);
}
@@ -316,23 +215,16 @@ public class AbstractServiceTest extends TestCase {
public void testThreadedServiceStartAndWaitStopAndWait() throws Throwable {
ThreadedService service = new ThreadedService();
- RecordingListener listener = RecordingListener.record(service);
+
service.start().get();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.awaitRunChecks();
- service.stopAndWait();
- assertEquals(State.TERMINATED, service.state());
+ service.stop().get();
+ assertEquals(Service.State.TERMINATED, service.state());
throwIfSet(thrownByExecutionThread);
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.TERMINATED),
- listener.getStateHistory());
}
public void testThreadedServiceStartStopIdempotence() throws Throwable {
@@ -340,13 +232,13 @@ public class AbstractServiceTest extends TestCase {
service.start();
service.start().get();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.awaitRunChecks();
service.stop();
service.stop().get();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
throwIfSet(thrownByExecutionThread);
}
@@ -357,13 +249,13 @@ public class AbstractServiceTest extends TestCase {
service.start().get();
service.start();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.awaitRunChecks();
service.stop().get();
service.stop();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
executionThread.join();
@@ -376,31 +268,17 @@ public class AbstractServiceTest extends TestCase {
service.start().get();
service.start().get();
- assertEquals(State.RUNNING, service.state());
+ assertEquals(Service.State.RUNNING, service.state());
service.awaitRunChecks();
service.stop().get();
service.stop().get();
- assertEquals(State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, service.state());
throwIfSet(thrownByExecutionThread);
}
- public void testManualServiceFailureIdempotence() {
- ManualSwitchedService service = new ManualSwitchedService();
- RecordingListener.record(service);
- service.start();
- service.notifyFailed(new Exception("1"));
- service.notifyFailed(new Exception("2"));
- try {
- service.startAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals("1", e.getCause().getMessage());
- }
- }
-
private class ThreadedService extends AbstractService {
final CountDownLatch hasConfirmedIsRunning = new CountDownLatch(1);
@@ -461,249 +339,53 @@ public class AbstractServiceTest extends TestCase {
public void testStopUnstartedService() throws Exception {
NoOpService service = new NoOpService();
- RecordingListener listener = RecordingListener.record(service);
-
- Future<State> stopResult = service.stop();
- assertEquals(State.TERMINATED, service.state());
- assertEquals(State.TERMINATED, stopResult.get());
+ Future<Service.State> stopResult = service.stop();
+ assertEquals(Service.State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, stopResult.get());
- Future<State> startResult = service.start();
- assertEquals(State.TERMINATED, service.state());
- assertEquals(State.TERMINATED, startResult.get());
- assertEquals(State.TERMINATED, Iterables.getOnlyElement(listener.getStateHistory()));
- }
-
- public void testFailingServiceStartAndWait() throws Exception {
- StartFailingService service = new StartFailingService();
- RecordingListener listener = RecordingListener.record(service);
-
- try {
- service.startAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals(EXCEPTION, e.getCause());
- }
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.FAILED),
- listener.getStateHistory());
- }
-
- public void testFailingServiceStopAndWait_stopFailing() throws Exception {
- StopFailingService service = new StopFailingService();
- RecordingListener listener = RecordingListener.record(service);
-
- service.startAndWait();
- try {
- service.stopAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals(EXCEPTION, e.getCause());
- }
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.FAILED),
- listener.getStateHistory());
- }
-
- public void testFailingServiceStopAndWait_runFailinging() throws Exception {
- RunFailingService service = new RunFailingService();
- RecordingListener listener = RecordingListener.record(service);
-
- service.startAndWait();
- try {
- service.stopAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals(EXCEPTION, e.getCause().getCause());
- }
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.FAILED),
- listener.getStateHistory());
+ Future<Service.State> startResult = service.start();
+ assertEquals(Service.State.TERMINATED, service.state());
+ assertEquals(Service.State.TERMINATED, startResult.get());
}
public void testThrowingServiceStartAndWait() throws Exception {
StartThrowingService service = new StartThrowingService();
- RecordingListener listener = RecordingListener.record(service);
try {
service.startAndWait();
fail();
} catch (UncheckedExecutionException e) {
- assertEquals(service.exception, e.getCause());
+ assertEquals(EXCEPTION, e.getCause());
}
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.FAILED),
- listener.getStateHistory());
}
public void testThrowingServiceStopAndWait_stopThrowing() throws Exception {
StopThrowingService service = new StopThrowingService();
- RecordingListener listener = RecordingListener.record(service);
service.startAndWait();
try {
service.stopAndWait();
fail();
} catch (UncheckedExecutionException e) {
- assertEquals(service.exception, e.getCause());
+ assertEquals(EXCEPTION, e.getCause());
}
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.STOPPING,
- State.FAILED),
- listener.getStateHistory());
}
public void testThrowingServiceStopAndWait_runThrowing() throws Exception {
RunThrowingService service = new RunThrowingService();
- RecordingListener listener = RecordingListener.record(service);
-
- service.startAndWait();
- try {
- service.stopAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals(service.exception, e.getCause().getCause());
- }
- assertEquals(
- ImmutableList.of(
- State.STARTING,
- State.RUNNING,
- State.FAILED),
- listener.getStateHistory());
- }
- public void testFailureCause_throwsIfNotFailed() {
- StopFailingService service = new StopFailingService();
- try {
- service.failureCause();
- fail();
- } catch (IllegalStateException e) {
- // expected
- }
service.startAndWait();
try {
- service.failureCause();
- fail();
- } catch (IllegalStateException e) {
- // expected
- }
- try {
service.stopAndWait();
fail();
} catch (UncheckedExecutionException e) {
- assertEquals(EXCEPTION, service.failureCause());
- assertEquals(EXCEPTION, e.getCause());
- }
- }
-
- public void testAddListenerAfterFailureDoesntCauseDeadlock() throws InterruptedException {
- final StartFailingService service = new StartFailingService();
- service.start();
- assertEquals(State.FAILED, service.state());
- service.addListener(new RecordingListener(service), MoreExecutors.sameThreadExecutor());
- Thread thread = new Thread() {
- @Override public void run() {
- // Internally start() grabs a lock, this could be any such method on AbstractService.
- service.start();
- }
- };
- thread.start();
- thread.join(100);
- assertFalse(thread + " is deadlocked", thread.isAlive());
- }
-
- public void testListenerDoesntDeadlockOnStartAndWaitFromRunning() throws Exception {
- final NoOpThreadedService service = new NoOpThreadedService();
- service.addListener(new Listener() {
- @Override public void starting() { }
- @Override public void running() {
- service.startAndWait();
- }
- @Override public void stopping(State from) { }
- @Override public void terminated(State from) { }
- @Override public void failed(State from, Throwable failure) { }
- }, MoreExecutors.sameThreadExecutor());
- service.start().get(10, TimeUnit.MILLISECONDS);
- service.stop();
- }
-
- public void testListenerDoesntDeadlockOnStopAndWaitFromTerminated() throws Exception {
- final NoOpThreadedService service = new NoOpThreadedService();
- service.addListener(new Listener() {
- @Override public void starting() { }
- @Override public void running() { }
- @Override public void stopping(State from) { }
- @Override public void terminated(State from) {
- service.stopAndWait();
- }
- @Override public void failed(State from, Throwable failure) { }
- }, MoreExecutors.sameThreadExecutor());
- service.startAndWait();
-
- Thread thread = new Thread() {
- @Override public void run() {
- service.stopAndWait();
- }
- };
- thread.start();
- thread.join(100);
- assertFalse(thread + " is deadlocked", thread.isAlive());
- }
-
- private static class NoOpThreadedService extends AbstractExecutionThreadService {
- @Override protected void run() throws Exception {}
- }
-
- private static class StartFailingService extends AbstractService {
- @Override protected void doStart() {
- notifyFailed(EXCEPTION);
- }
-
- @Override protected void doStop() {
- fail();
- }
- }
-
- private static class RunFailingService extends AbstractService {
- @Override protected void doStart() {
- notifyStarted();
- notifyFailed(EXCEPTION);
- }
-
- @Override protected void doStop() {
- fail();
- }
- }
-
- private static class StopFailingService extends AbstractService {
- @Override protected void doStart() {
- notifyStarted();
- }
-
- @Override protected void doStop() {
- notifyFailed(EXCEPTION);
+ assertEquals(EXCEPTION, e.getCause().getCause());
}
}
private static class StartThrowingService extends AbstractService {
-
- final RuntimeException exception = new RuntimeException("deliberate");
-
@Override protected void doStart() {
- throw exception;
+ notifyFailed(EXCEPTION);
}
@Override protected void doStop() {
@@ -712,12 +394,9 @@ public class AbstractServiceTest extends TestCase {
}
private static class RunThrowingService extends AbstractService {
-
- final RuntimeException exception = new RuntimeException("deliberate");
-
@Override protected void doStart() {
notifyStarted();
- throw exception;
+ notifyFailed(EXCEPTION);
}
@Override protected void doStop() {
@@ -726,143 +405,14 @@ public class AbstractServiceTest extends TestCase {
}
private static class StopThrowingService extends AbstractService {
-
- final RuntimeException exception = new RuntimeException("deliberate");
-
@Override protected void doStart() {
notifyStarted();
}
@Override protected void doStop() {
- throw exception;
- }
- }
-
- private static class RecordingListener implements Listener {
- static RecordingListener record(Service service) {
- RecordingListener listener = new RecordingListener(service);
- service.addListener(listener, MoreExecutors.sameThreadExecutor());
- return listener;
- }
-
- final Service service;
-
- RecordingListener(Service service) {
- this.service = service;
- }
-
- @GuardedBy("this")
- final List<State> stateHistory = Lists.newArrayList();
- final CountDownLatch completionLatch = new CountDownLatch(1);
-
- ImmutableList<State> getStateHistory() throws Exception {
- completionLatch.await();
- synchronized (this) {
- return ImmutableList.copyOf(stateHistory);
- }
- }
-
- @Override public synchronized void starting() {
- assertTrue(stateHistory.isEmpty());
- assertNotSame(State.NEW, service.state());
- stateHistory.add(State.STARTING);
- }
-
- @Override public synchronized void running() {
- assertEquals(State.STARTING, Iterables.getOnlyElement(stateHistory));
- stateHistory.add(State.RUNNING);
- assertTrue(service.start().isDone());
- assertEquals(State.RUNNING, service.startAndWait());
- assertNotSame(State.STARTING, service.state());
- }
-
- @Override public synchronized void stopping(State from) {
- assertEquals(from, Iterables.getLast(stateHistory));
- stateHistory.add(State.STOPPING);
- if (from == State.STARTING) {
- assertTrue(service.start().isDone());
- assertEquals(State.STOPPING, service.startAndWait());
- }
- assertNotSame(from, service.state());
- }
-
- @Override public synchronized void terminated(State from) {
- assertEquals(from, Iterables.getLast(stateHistory, State.NEW));
- stateHistory.add(State.TERMINATED);
- assertEquals(State.TERMINATED, service.state());
- assertTrue(service.start().isDone());
- if (from == State.NEW) {
- assertEquals(State.TERMINATED, service.startAndWait());
- }
- assertTrue(service.stop().isDone());
- assertEquals(State.TERMINATED, service.stopAndWait());
- completionLatch.countDown();
- }
-
- @Override public synchronized void failed(State from, Throwable failure) {
- assertEquals(from, Iterables.getLast(stateHistory));
- stateHistory.add(State.FAILED);
- assertEquals(State.FAILED, service.state());
- if (from == State.STARTING) {
- try {
- service.startAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- assertEquals(failure, e.getCause());
- }
- }
- try {
- service.stopAndWait();
- fail();
- } catch (UncheckedExecutionException e) {
- if (from == State.STOPPING) {
- assertEquals(failure, e.getCause());
- } else {
- assertEquals(failure, e.getCause().getCause());
- }
- }
- completionLatch.countDown();
+ notifyFailed(EXCEPTION);
}
}
- public void testNotifyStartedWhenNotStarting() {
- AbstractService service = new DefaultService();
- try {
- service.notifyStarted();
- fail();
- } catch (IllegalStateException expected) {}
- }
-
- public void testNotifyStoppedWhenNotRunning() {
- AbstractService service = new DefaultService();
- try {
- service.notifyStopped();
- fail();
- } catch (IllegalStateException expected) {}
- }
-
- public void testNotifyFailedWhenNotStarted() {
- AbstractService service = new DefaultService();
- try {
- service.notifyFailed(new Exception());
- fail();
- } catch (IllegalStateException expected) {}
- }
-
- public void testNotifyFailedWhenTerminated() {
- NoOpService service = new NoOpService();
- service.startAndWait();
- service.stopAndWait();
- try {
- service.notifyFailed(new Exception());
- fail();
- } catch (IllegalStateException expected) {}
- }
-
- private static class DefaultService extends AbstractService {
- @Override protected void doStart() {}
- @Override protected void doStop() {}
- }
-
private static final Exception EXCEPTION = new Exception();
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java b/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java
index 7ad3a4a..f3aa63f 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java
@@ -14,7 +14,6 @@
package com.google.common.util.concurrent;
import junit.framework.*;
-
import java.util.Arrays;
/**
diff --git a/guava-tests/test/com/google/common/util/concurrent/AtomicLongMapTest.java b/guava-tests/test/com/google/common/util/concurrent/AtomicLongMapTest.java
index 8746e33..8bffaa1 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AtomicLongMapTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AtomicLongMapTest.java
@@ -1,23 +1,7 @@
-/*
- * Copyright (C) 2011 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.
- */
+// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.common.util.concurrent;
-import com.google.common.annotations.GwtCompatible;
-import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.testing.NullPointerTester;
@@ -35,17 +19,15 @@ import java.util.concurrent.atomic.AtomicLong;
/**
* Tests for {@link AtomicLongMap}.
*
- * @author mike nonemacher
+ * @author schmoe@google.com (mike nonemacher)
*/
-@GwtCompatible(emulated = true)
public class AtomicLongMapTest extends TestCase {
private static final int ITERATIONS = 100;
private static final int MAX_ADDEND = 100;
private Random random = new Random(301);
- @GwtIncompatible("NullPointerTester")
- public void testNulls() {
+ public void testNulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicConstructors(AtomicLongMap.class);
tester.testAllPublicStaticMethods(AtomicLongMap.class);
@@ -554,7 +536,6 @@ public class AtomicLongMapTest extends TestCase {
assertFalse(map.replace("a", 1L, 0L));
}
- @GwtIncompatible("threads")
public void testModify_basher() throws InterruptedException {
int nTasks = 3000;
int nThreads = 100;
diff --git a/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java b/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java
index 5a19625..66f2b13 100644
--- a/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java
@@ -82,7 +82,7 @@ public class AtomicsTest extends TestCase {
}
}
- public void testNullPointers() {
+ public void testNullPointers() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicConstructors(Atomics.class); // there aren't any
tester.testAllPublicStaticMethods(Atomics.class);
diff --git a/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java b/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
deleted file mode 100644
index b39601f..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java
+++ /dev/null
@@ -1,581 +0,0 @@
-/*
- * Copyright (C) 2011 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 com.google.common.base.Joiner;
-import com.google.common.util.concurrent.CycleDetectingLockFactory.OrderedLockGraphNodesCreator;
-import com.google.common.util.concurrent.CycleDetectingLockFactory.Policies;
-import com.google.common.util.concurrent.CycleDetectingLockFactory.Policy;
-import com.google.common.util.concurrent.CycleDetectingLockFactory.PotentialDeadlockException;
-
-import junit.framework.TestCase;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Unittests for {@link CycleDetectingLockFactory}.
- *
- * @author Darick Tong
- */
-public class CycleDetectingLockFactoryTest extends TestCase {
-
- private ReentrantLock lockA;
- private ReentrantLock lockB;
- private ReentrantLock lockC;
- private ReentrantReadWriteLock.ReadLock readLockA;
- private ReentrantReadWriteLock.ReadLock readLockB;
- private ReentrantReadWriteLock.ReadLock readLockC;
- private ReentrantReadWriteLock.WriteLock writeLockA;
- private ReentrantReadWriteLock.WriteLock writeLockB;
- private ReentrantReadWriteLock.WriteLock writeLockC;
- private ReentrantLock lock1;
- private ReentrantLock lock2;
- private ReentrantLock lock3;
- private ReentrantLock lock01;
- private ReentrantLock lock02;
- private ReentrantLock lock03;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- CycleDetectingLockFactory factory =
- CycleDetectingLockFactory.newInstance(Policies.THROW);
- lockA = factory.newReentrantLock("LockA");
- lockB = factory.newReentrantLock("LockB");
- lockC = factory.newReentrantLock("LockC");
- ReentrantReadWriteLock readWriteLockA =
- factory.newReentrantReadWriteLock("ReadWriteA");
- ReentrantReadWriteLock readWriteLockB =
- factory.newReentrantReadWriteLock("ReadWriteB");
- ReentrantReadWriteLock readWriteLockC =
- factory.newReentrantReadWriteLock("ReadWriteC");
- readLockA = readWriteLockA.readLock();
- readLockB = readWriteLockB.readLock();
- readLockC = readWriteLockC.readLock();
- writeLockA = readWriteLockA.writeLock();
- writeLockB = readWriteLockB.writeLock();
- writeLockC = readWriteLockC.writeLock();
-
- CycleDetectingLockFactory.WithExplicitOrdering<MyOrder> factory2 =
- newInstanceWithExplicitOrdering(MyOrder.class, Policies.THROW);
- lock1 = factory2.newReentrantLock(MyOrder.FIRST);
- lock2 = factory2.newReentrantLock(MyOrder.SECOND);
- lock3 = factory2.newReentrantLock(MyOrder.THIRD);
-
- CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory3 =
- newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW);
- lock01 = factory3.newReentrantLock(OtherOrder.FIRST);
- lock02 = factory3.newReentrantLock(OtherOrder.SECOND);
- lock03 = factory3.newReentrantLock(OtherOrder.THIRD);
- }
-
- // In the unittest, create each ordered factory with its own set of lock
- // graph nodes (as opposed to using the static per-Enum map) to avoid
- // conflicts across different test runs.
- private <E extends Enum<E>> CycleDetectingLockFactory.WithExplicitOrdering<E>
- newInstanceWithExplicitOrdering(Class<E> enumClass, Policy policy) {
- OrderedLockGraphNodesCreator nodeCreator =
- new OrderedLockGraphNodesCreator();
- return new CycleDetectingLockFactory.WithExplicitOrdering<E>(
- policy, nodeCreator.createNodesFor(enumClass));
- }
-
- public void testDeadlock_twoLocks() {
- // Establish an acquisition order of lockA -> lockB.
- lockA.lock();
- lockB.lock();
- lockA.unlock();
- lockB.unlock();
-
- // The opposite order should fail (Policies.THROW).
- PotentialDeadlockException firstException = null;
- lockB.lock();
- try {
- lockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "LockB -> LockA", "LockA -> LockB");
- firstException = expected;
- }
-
- // Second time should also fail, with a cached causal chain.
- try {
- lockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "LockB -> LockA", "LockA -> LockB");
- // The causal chain should be cached.
- assertSame(firstException.getCause(), expected.getCause());
- }
-
- // lockA should work after lockB is released.
- lockB.unlock();
- lockA.lock();
- }
-
- // Tests transitive deadlock detection.
- public void testDeadlock_threeLocks() {
- // Establish an ordering from lockA -> lockB.
- lockA.lock();
- lockB.lock();
- lockB.unlock();
- lockA.unlock();
-
- // Establish an ordering from lockB -> lockC.
- lockB.lock();
- lockC.lock();
- lockB.unlock();
-
- // lockC -> lockA should fail.
- try {
- lockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected, "LockC -> LockA", "LockB -> LockC", "LockA -> LockB");
- }
- }
-
- public void testReentrancy_noDeadlock() {
- lockA.lock();
- lockB.lock();
- lockA.lock(); // Should not assert on lockB -> reentrant(lockA)
- }
-
- public void testExplicitOrdering_noViolations() {
- lock1.lock();
- lock3.lock();
- lock3.unlock();
- lock2.lock();
- lock3.lock();
- }
-
- public void testExplicitOrdering_violations() {
- lock3.lock();
- try {
- lock2.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "MyOrder.THIRD -> MyOrder.SECOND");
- }
-
- try {
- lock1.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "MyOrder.THIRD -> MyOrder.FIRST");
- }
-
- lock3.unlock();
- lock2.lock();
-
- try {
- lock1.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "MyOrder.SECOND -> MyOrder.FIRST");
- }
- }
-
- public void testDifferentOrderings_noViolations() {
- lock3.lock(); // MyOrder, ordinal() == 3
- lock01.lock(); // OtherOrder, ordinal() == 1
- }
-
- public void testExplicitOrderings_generalCycleDetection() {
- lock3.lock(); // MyOrder, ordinal() == 3
- lock01.lock(); // OtherOrder, ordinal() == 1
-
- lock3.unlock();
- try {
- lock3.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "OtherOrder.FIRST -> MyOrder.THIRD",
- "MyOrder.THIRD -> OtherOrder.FIRST");
- }
-
- lockA.lock();
- lock01.unlock();
- lockB.lock();
- lockA.unlock();
-
- try {
- lock01.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "LockB -> OtherOrder.FIRST",
- "LockA -> LockB",
- "OtherOrder.FIRST -> LockA");
- }
- }
-
- public void testExplicitOrdering_cycleWithUnorderedLock() {
- Lock myLock = CycleDetectingLockFactory.newInstance(Policies.THROW)
- .newReentrantLock("MyLock");
- lock03.lock();
- myLock.lock();
- lock03.unlock();
-
- try {
- lock01.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "MyLock -> OtherOrder.FIRST",
- "OtherOrder.THIRD -> MyLock",
- "OtherOrder.FIRST -> OtherOrder.THIRD");
- }
- }
-
- public void testExplicitOrdering_reentrantAcquisition() {
- CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory =
- newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW);
- Lock lockA = factory.newReentrantReadWriteLock(OtherOrder.FIRST).readLock();
- Lock lockB = factory.newReentrantLock(OtherOrder.SECOND);
-
- lockA.lock();
- lockA.lock();
- lockB.lock();
- lockB.lock();
- lockA.unlock();
- lockA.unlock();
- lockB.unlock();
- lockB.unlock();
- }
-
- public void testExplicitOrdering_acquiringMultipleLocksWithSameRank() {
- CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory =
- newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW);
- Lock lockA = factory.newReentrantLock(OtherOrder.FIRST);
- Lock lockB = factory.newReentrantReadWriteLock(OtherOrder.FIRST).readLock();
-
- lockA.lock();
- try {
- lockB.lock();
- fail("Expected IllegalStateException");
- } catch (IllegalStateException expected) {
- }
-
- lockA.unlock();
- lockB.lock();
- }
-
- public void testReadLock_deadlock() {
- readLockA.lock(); // Establish an ordering from readLockA -> lockB.
- lockB.lock();
- lockB.unlock();
- readLockA.unlock();
-
- lockB.lock();
- try {
- readLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB");
- }
- }
-
- public void testReadLock_transitive() {
- readLockA.lock(); // Establish an ordering from readLockA -> lockB.
- lockB.lock();
- lockB.unlock();
- readLockA.unlock();
-
- // Establish an ordering from lockB -> readLockC.
- lockB.lock();
- readLockC.lock();
- lockB.unlock();
- readLockC.unlock();
-
- // readLockC -> readLockA
- readLockC.lock();
- try {
- readLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "ReadWriteC -> ReadWriteA",
- "LockB -> ReadWriteC",
- "ReadWriteA -> LockB");
- }
- }
-
- public void testWriteLock_threeLockDeadLock() {
- // Establish an ordering from writeLockA -> writeLockB.
- writeLockA.lock();
- writeLockB.lock();
- writeLockB.unlock();
- writeLockA.unlock();
-
- // Establish an ordering from writeLockB -> writeLockC.
- writeLockB.lock();
- writeLockC.lock();
- writeLockB.unlock();
-
- // writeLockC -> writeLockA should fail.
- try {
- writeLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "ReadWriteC -> ReadWriteA",
- "ReadWriteB -> ReadWriteC",
- "ReadWriteA -> ReadWriteB");
- }
- }
-
- public void testWriteToReadLockDowngrading() {
- writeLockA.lock(); // writeLockA downgrades to readLockA
- readLockA.lock();
- writeLockA.unlock();
-
- lockB.lock(); // readLockA -> lockB
- readLockA.unlock();
-
- // lockB -> writeLockA should fail
- try {
- writeLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB");
- }
- }
-
- public void testReadWriteLockDeadlock() {
- writeLockA.lock(); // Establish an ordering from writeLockA -> lockB
- lockB.lock();
- writeLockA.unlock();
- lockB.unlock();
-
- // lockB -> readLockA should fail.
- lockB.lock();
- try {
- readLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB");
- }
- }
-
- public void testReadWriteLockDeadlock_transitive() {
- readLockA.lock(); // Establish an ordering from readLockA -> lockB
- lockB.lock();
- readLockA.unlock();
- lockB.unlock();
-
- // Establish an ordering from lockB -> lockC
- lockB.lock();
- lockC.lock();
- lockB.unlock();
- lockC.unlock();
-
- // lockC -> writeLockA should fail.
- lockC.lock();
- try {
- writeLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected,
- "LockC -> ReadWriteA",
- "LockB -> LockC",
- "ReadWriteA -> LockB");
- }
- }
-
- public void testReadWriteLockDeadlock_treatedEquivalently() {
- readLockA.lock(); // readLockA -> writeLockB
- writeLockB.lock();
- readLockA.unlock();
- writeLockB.unlock();
-
- // readLockB -> writeLockA should fail.
- readLockB.lock();
- try {
- writeLockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(
- expected, "ReadWriteB -> ReadWriteA", "ReadWriteA -> ReadWriteB");
- }
- }
-
- public void testDifferentLockFactories() {
- CycleDetectingLockFactory otherFactory =
- CycleDetectingLockFactory.newInstance(Policies.WARN);
- ReentrantLock lockD = otherFactory.newReentrantLock("LockD");
-
- // lockA -> lockD
- lockA.lock();
- lockD.lock();
- lockA.unlock();
- lockD.unlock();
-
- // lockD -> lockA should fail even though lockD is from a different factory.
- lockD.lock();
- try {
- lockA.lock();
- fail("Expected PotentialDeadlockException");
- } catch (PotentialDeadlockException expected) {
- checkMessage(expected, "LockD -> LockA", "LockA -> LockD");
- }
- }
-
- public void testDifferentLockFactories_policyExecution() {
- CycleDetectingLockFactory otherFactory =
- CycleDetectingLockFactory.newInstance(Policies.WARN);
- ReentrantLock lockD = otherFactory.newReentrantLock("LockD");
-
- // lockD -> lockA
- lockD.lock();
- lockA.lock();
- lockA.unlock();
- lockD.unlock();
-
- // lockA -> lockD should warn but otherwise succeed because lockD was
- // created by a factory with the WARN policy.
- lockA.lock();
- lockD.lock();
- }
-
- public void testReentrantLock_tryLock() throws Exception {
- LockingThread thread = new LockingThread(lockA);
- thread.start();
-
- thread.waitUntilHoldingLock();
- assertFalse(lockA.tryLock());
-
- thread.releaseLockAndFinish();
- assertTrue(lockA.tryLock());
- }
-
- public void testReentrantWriteLock_tryLock() throws Exception {
- LockingThread thread = new LockingThread(writeLockA);
- thread.start();
-
- thread.waitUntilHoldingLock();
- assertFalse(writeLockA.tryLock());
- assertFalse(readLockA.tryLock());
-
- thread.releaseLockAndFinish();
- assertTrue(writeLockA.tryLock());
- assertTrue(readLockA.tryLock());
- }
-
- public void testReentrantReadLock_tryLock() throws Exception {
- LockingThread thread = new LockingThread(readLockA);
- thread.start();
-
- thread.waitUntilHoldingLock();
- assertFalse(writeLockA.tryLock());
- assertTrue(readLockA.tryLock());
- readLockA.unlock();
-
- thread.releaseLockAndFinish();
- assertTrue(writeLockA.tryLock());
- assertTrue(readLockA.tryLock());
- }
-
- private static class LockingThread extends Thread {
- final CountDownLatch locked = new CountDownLatch(1);
- final CountDownLatch finishLatch = new CountDownLatch(1);
- final Lock lock;
-
- LockingThread(Lock lock) {
- this.lock = lock;
- }
-
- @Override
- public void run() {
- lock.lock();
- try {
- locked.countDown();
- finishLatch.await(1, TimeUnit.MINUTES);
- } catch (InterruptedException e) {
- fail(e.toString());
- } finally {
- lock.unlock();
- }
- }
-
- void waitUntilHoldingLock() throws InterruptedException {
- locked.await(1, TimeUnit.MINUTES);
- }
-
- void releaseLockAndFinish() throws InterruptedException {
- finishLatch.countDown();
- this.join(10000);
- assertFalse(this.isAlive());
- }
- }
-
- public void testReentrantReadWriteLock_implDoesNotExposeShadowedLocks() {
- assertEquals(
- "Unexpected number of public methods in ReentrantReadWriteLock. " +
- "The correctness of CycleDetectingReentrantReadWriteLock depends on " +
- "the fact that the shadowed ReadLock and WriteLock are never used or " +
- "exposed by the superclass implementation. If the implementation has " +
- "changed, the code must be re-inspected to ensure that the " +
- "assumption is still valid.",
- 24, ReentrantReadWriteLock.class.getMethods().length);
- }
-
- private enum MyOrder {
- FIRST, SECOND, THIRD;
- }
-
- private enum OtherOrder {
- FIRST, SECOND, THIRD;
- }
-
- // Given a sequence of lock acquisition descriptions
- // (e.g. "LockA -> LockB", "LockB -> LockC", ...)
- // Checks that the exception.getMessage() matches a regex of the form:
- // "LockA -> LockB \b.*\b LockB -> LockC \b.*\b LockC -> LockA"
- private void checkMessage(
- IllegalStateException exception, String... expectedLockCycle) {
- String regex = Joiner.on("\\b.*\\b").join(expectedLockCycle);
- assertContainsRegex(regex, exception.getMessage());
- }
-
- // TODO(cpovirk): consider adding support for regex to Truth
- private static void assertContainsRegex(String expectedRegex, String actual) {
- Pattern pattern = Pattern.compile(expectedRegex);
- Matcher matcher = pattern.matcher(actual);
- if (!matcher.find()) {
- String actualDesc = (actual == null) ? "null" : ('<' + actual + '>');
- fail("expected to contain regex:<" + expectedRegex + "> but was:"
- + actualDesc);
- }
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java b/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java
index 92d9768..a4a2a8d 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java
@@ -27,7 +27,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
/**
* Unit tests for {@link ExecutionList}.
@@ -37,10 +36,10 @@ import java.util.concurrent.atomic.AtomicInteger;
*/
public class ExecutionListTest extends TestCase {
- private final ExecutionList list = new ExecutionList();
+ protected ExecutionList list = new ExecutionList();
+ protected Executor exec = Executors.newCachedThreadPool();
public void testRunOnPopulatedList() throws Exception {
- Executor exec = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(3);
list.add(new MockRunnable(countDownLatch), exec);
list.add(new MockRunnable(countDownLatch), exec);
@@ -53,56 +52,13 @@ public class ExecutionListTest extends TestCase {
assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
}
- public void testExecute_idempotent() {
- final AtomicInteger runCalled = new AtomicInteger();
- list.add(new Runnable() {
- @Override public void run() {
- runCalled.getAndIncrement();
- }
- }, MoreExecutors.sameThreadExecutor());
- list.execute();
- assertEquals(1, runCalled.get());
- list.execute();
- assertEquals(1, runCalled.get());
- }
-
- public void testExecute_idempotentConcurrently() throws InterruptedException {
- final CountDownLatch okayToRun = new CountDownLatch(1);
- final AtomicInteger runCalled = new AtomicInteger();
- list.add(new Runnable() {
- @Override public void run() {
- try {
- okayToRun.await();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new RuntimeException(e);
- }
- runCalled.getAndIncrement();
- }
- }, MoreExecutors.sameThreadExecutor());
- Runnable execute = new Runnable() {
- @Override public void run() {
- list.execute();
- }
- };
- Thread thread1 = new Thread(execute);
- Thread thread2 = new Thread(execute);
- thread1.start();
- thread2.start();
- assertEquals(0, runCalled.get());
- okayToRun.countDown();
- thread1.join();
- thread2.join();
- assertEquals(1, runCalled.get());
- }
-
public void testAddAfterRun() throws Exception {
// Run the previous test
testRunOnPopulatedList();
// If it passed, then verify an Add will be executed without calling run
CountDownLatch countDownLatch = new CountDownLatch(1);
- list.add(new MockRunnable(countDownLatch), Executors.newCachedThreadPool());
+ list.add(new MockRunnable(countDownLatch), exec);
assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
}
@@ -113,19 +69,24 @@ public class ExecutionListTest extends TestCase {
this.countDownLatch = countDownLatch;
}
- @Override public void run() {
+ @Override
+ public void run() {
countDownLatch.countDown();
}
}
public void testExceptionsCaught() {
+ ExecutionList list = new ExecutionList();
list.add(THROWING_RUNNABLE, sameThreadExecutor());
list.execute();
list.add(THROWING_RUNNABLE, sameThreadExecutor());
}
- public void testNulls() {
- new NullPointerTester().testAllPublicInstanceMethods(new ExecutionList());
+ public void testNulls() throws Exception {
+ NullPointerTester tester = new NullPointerTester();
+ tester.setDefault(Executor.class, sameThreadExecutor());
+ tester.setDefault(Runnable.class, DO_NOTHING);
+ tester.testAllPublicInstanceMethods(new ExecutionList());
}
private static final Runnable THROWING_RUNNABLE = new Runnable() {
@@ -134,6 +95,7 @@ public class ExecutionListTest extends TestCase {
}
};
private static final Runnable DO_NOTHING = new Runnable() {
- @Override public void run() {}
+ @Override public void run() {
+ }
};
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingBlockingQueueTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingBlockingQueueTest.java
deleted file mode 100644
index c32eb3f..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingBlockingQueueTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2012 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 junit.framework.TestCase;
-
-/**
- * Unit tests for {@link ForwardingBlockingQueue}
- */
-public class ForwardingBlockingQueueTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingBlockingQueue.class);
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingCheckedFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingCheckedFutureTest.java
index 1a642be..b78c287 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingCheckedFutureTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ForwardingCheckedFutureTest.java
@@ -16,15 +16,99 @@
package com.google.common.util.concurrent;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+
+import com.google.common.util.concurrent.ForwardingCheckedFuture.SimpleForwardingCheckedFuture;
+
import junit.framework.TestCase;
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
/**
* Test for {@link ForwardingCheckedFuture}
*
- * @author Ben Yu
+ * @author Anthony Zana
*/
public class ForwardingCheckedFutureTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingCheckedFuture.class);
+ private static final String VALUE = "delegated";
+ private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
+
+ @SuppressWarnings("unchecked")
+ private CheckedFuture<String, IOException> delegate =
+ createMock(CheckedFuture.class);
+
+ private TestDelegateFuture forwarded = new TestDelegateFuture();
+ private TestSimpleFuture simple = new TestSimpleFuture();
+
+ public void testCheckedGet() throws IOException {
+ expect(delegate.checkedGet()).andReturn(VALUE).times(2);
+ replay(delegate);
+ assertEquals(VALUE, forwarded.checkedGet());
+ assertEquals(VALUE, simple.checkedGet());
+ verify(delegate);
+ }
+
+ public void testTimedCheckedGet() throws TimeoutException, IOException {
+ expect(delegate.checkedGet(100, TIME_UNIT)).andReturn(VALUE).times(2);
+ replay(delegate);
+ assertEquals(VALUE, forwarded.checkedGet(100, TIME_UNIT));
+ assertEquals(VALUE, simple.checkedGet(100, TIME_UNIT));
+ verify(delegate);
+ }
+
+ public void testTimedCheckedGet_timeout()
+ throws IOException, TimeoutException {
+ expect(delegate.checkedGet(100, TIME_UNIT))
+ .andThrow(new TimeoutException()).times(2);
+ replay(delegate);
+ try {
+ forwarded.checkedGet(100, TIME_UNIT);
+ fail();
+ } catch (TimeoutException expected) {}
+ try {
+ simple.checkedGet(100, TIME_UNIT);
+ fail();
+ } catch (TimeoutException expected) {}
+ verify(delegate);
+ }
+
+ public void testCheckedGetException() throws IOException {
+ IOException expected = new IOException("expected");
+ expect(delegate.checkedGet()).andThrow(expected).times(2);
+ replay(delegate);
+ try {
+ delegate.checkedGet();
+ fail();
+ } catch (IOException e) {
+ assertEquals(expected.getMessage(), e.getMessage());
+ }
+ try {
+ simple.checkedGet();
+ fail();
+ } catch (IOException e) {
+ assertEquals(expected.getMessage(), e.getMessage());
+ }
+ verify(delegate);
+ }
+
+ private class TestDelegateFuture
+ extends ForwardingCheckedFuture<String, IOException> {
+ @Override
+ protected CheckedFuture<String, IOException> delegate() {
+ return delegate;
+ }
+ }
+
+ private class TestSimpleFuture
+ extends SimpleForwardingCheckedFuture<String, IOException> {
+ public TestSimpleFuture() {
+ super(delegate);
+ }
}
+
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingExecutorServiceTest.java
deleted file mode 100644
index 15f1e0e..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingExecutorServiceTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2012 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 junit.framework.TestCase;
-
-/**
- * Unit tests for {@link ForwardingExecutorService}
- */
-public class ForwardingExecutorServiceTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingExecutorService.class);
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingFutureTest.java
deleted file mode 100644
index 4ce9ebf..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingFutureTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2012 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 junit.framework.TestCase;
-
-/**
- * Unit tests for {@link ForwardingFuture}
- */
-public class ForwardingFutureTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingFuture.class);
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingListenableFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingListenableFutureTest.java
index 827f50e..4424e8d 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingListenableFutureTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ForwardingListenableFutureTest.java
@@ -21,10 +21,48 @@ import junit.framework.TestCase;
/**
* Tests for {@link ForwardingListenableFuture}.
*
- * @author Ben Yu
+ * @author Shardul Deo
*/
public class ForwardingListenableFutureTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingListenableFuture.class);
+
+ private SettableFuture<String> delegate;
+ private ListenableFuture<String> forwardingFuture;
+
+ private ListenableFutureTester tester;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ delegate = SettableFuture.create();
+ forwardingFuture = new ForwardingListenableFuture<String>() {
+ @Override
+ protected ListenableFuture<String> delegate() {
+ return delegate;
+ }
+ };
+ tester = new ListenableFutureTester(forwardingFuture);
+ tester.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ tester.tearDown();
+ super.tearDown();
+ }
+
+ public void testCompletedFuture() throws Exception {
+ delegate.set("foo");
+ tester.testCompletedFuture("foo");
+ }
+
+ public void testCancelledFuture() throws Exception {
+ delegate.cancel(true); // parameter is ignored
+ tester.testCancelledFuture();
+ }
+
+ public void testFailedFuture() throws Exception {
+ delegate.setException(new Exception("failed"));
+ tester.testFailedFuture("failed");
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingListeningExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingListeningExecutorServiceTest.java
deleted file mode 100644
index d4ebd61..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingListeningExecutorServiceTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2012 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 junit.framework.TestCase;
-
-/**
- * Unit tests for {@link ForwardingListeningExecutorService}
- */
-public class ForwardingListeningExecutorServiceTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingListeningExecutorService.class);
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
deleted file mode 100644
index edc48a9..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTester.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2012 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 com.google.common.base.Function;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ForwardingObject;
-import com.google.common.collect.Iterables;
-import com.google.common.testing.ForwardingWrapperTester;
-
-import org.easymock.EasyMock;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-
-/**
- * Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
- *
- * @author Ben Yu
- */
-final class ForwardingObjectTester {
-
- private static final Method DELEGATE_METHOD;
- static {
- try {
- DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate");
- DELEGATE_METHOD.setAccessible(true);
- } catch (SecurityException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new AssertionError(e);
- }
- }
-
- /**
- * Ensures that all interface methods of {@code forwarderClass} are forwarded to the
- * {@link ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one
- * interface.
- */
- static <T extends ForwardingObject> void testForwardingObject(final Class<T> forwarderClass) {
- @SuppressWarnings("unchecked") // super interface type of T
- Class<? super T> interfaceType = (Class<? super T>)
- Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces()));
- new ForwardingWrapperTester().testForwarding(interfaceType, new Function<Object, T>() {
- @Override public T apply(Object delegate) {
- T mock = EasyMock.createMockBuilder(forwarderClass)
- .addMockedMethod(DELEGATE_METHOD)
- .createMock();
- try {
- DELEGATE_METHOD.invoke(mock);
- } catch (Exception e) {
- throw Throwables.propagate(e);
- }
- EasyMock.expectLastCall().andStubReturn(delegate);
- EasyMock.replay(mock);
- return mock;
- }
- });
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTesterTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTesterTest.java
deleted file mode 100644
index eae45bc..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingObjectTesterTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2012 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 com.google.common.collect.ForwardingObject;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for {@link ForwardingObjectTester}.
- *
- * @author Ben Yu
- */
-public class ForwardingObjectTesterTest extends TestCase {
-
- public void testFailsToForward() {
- try {
- ForwardingObjectTester.testForwardingObject(FailToForward.class);
- } catch (AssertionError expected) {
- return;
- }
- fail("Should have thrown");
- }
-
- public void testSuccessfulForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardToDelegate.class);
- }
-
- private static abstract class FailToForward extends ForwardingObject implements Runnable {
- @Override public void run() {}
- }
-
- private static abstract class ForwardToDelegate extends ForwardingObject implements Runnable {
- @Override public void run() {
- delegate().run();
- }
- @Override protected abstract Runnable delegate();
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ForwardingServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/ForwardingServiceTest.java
deleted file mode 100644
index e18b00e..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/ForwardingServiceTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2012 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 junit.framework.TestCase;
-
-/**
- * Unit tests for {@link ForwardingService}
- */
-public class ForwardingServiceTest extends TestCase {
- public void testForwarding() {
- ForwardingObjectTester.testForwardingObject(ForwardingService.class);
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
index 44e759b..ea9a3da 100644
--- a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
@@ -23,12 +23,10 @@ import static com.google.common.util.concurrent.Futures.getUnchecked;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.successfulAsList;
-import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
-import static org.easymock.EasyMock.expect;
-import static org.truth0.Truth.ASSERT;
+import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.base.Function;
import com.google.common.base.Functions;
@@ -37,7 +35,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
-import com.google.common.testing.ClassSanityTester;
+import com.google.common.testing.NullPointerTester;
import com.google.common.util.concurrent.ForwardingFuture.SimpleForwardingFuture;
import junit.framework.AssertionFailedError;
@@ -56,12 +54,9 @@ import java.util.concurrent.CountDownLatch;
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.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.logging.Handler;
-import java.util.logging.LogRecord;
import javax.annotation.Nullable;
@@ -127,27 +122,6 @@ public class FuturesTest extends TestCase {
}
}
- public void testImmediateFailedFuture_cancellationException() throws Exception {
- CancellationException exception = new CancellationException();
- ListenableFuture<String> future =
- Futures.immediateFailedFuture(exception);
-
- try {
- future.get(0L, TimeUnit.MILLISECONDS);
- fail("This call was supposed to throw an ExecutionException");
- } catch (ExecutionException expected) {
- // This is good and expected
- assertSame(exception, expected.getCause());
- assertFalse(future.isCancelled());
- }
- }
-
- public void testImmediateCancelledFuture() throws Exception {
- ListenableFuture<String> future =
- Futures.immediateCancelledFuture();
- assertTrue(future.isCancelled());
- }
-
private static class MyException extends Exception {}
public void testImmediateCheckedFuture() throws Exception {
@@ -220,61 +194,6 @@ public class FuturesTest extends TestCase {
assertSame(barChild, bar);
}
- public void testTransform_ListenableFuture_cancelPropagatesToInput() throws Exception {
- SettableFuture<Foo> input = SettableFuture.create();
- AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
- @Override public ListenableFuture<Bar> apply(Foo unused) {
- fail("Unexpeted call to apply.");
- return null;
- }
- };
- assertTrue(Futures.transform(input, function).cancel(false));
- assertTrue(input.isCancelled());
- assertFalse(input.wasInterrupted());
- }
-
- public void testTransform_ListenableFuture_interruptPropagatesToInput()
- throws Exception {
- SettableFuture<Foo> input = SettableFuture.create();
- AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
- @Override public ListenableFuture<Bar> apply(Foo unused) {
- fail("Unexpeted call to apply.");
- return null;
- }
- };
- assertTrue(Futures.transform(input, function).cancel(true));
- assertTrue(input.isCancelled());
- assertTrue(input.wasInterrupted());
- }
-
- public void testTransform_ListenableFuture_cancelPropagatesToAsyncOutput()
- throws Exception {
- ListenableFuture<Foo> immediate = Futures.immediateFuture(new Foo());
- final SettableFuture<Bar> secondary = SettableFuture.create();
- AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
- @Override public ListenableFuture<Bar> apply(Foo unused) {
- return secondary;
- }
- };
- assertTrue(Futures.transform(immediate, function).cancel(false));
- assertTrue(secondary.isCancelled());
- assertFalse(secondary.wasInterrupted());
- }
-
- public void testTransform_ListenableFuture_interruptPropagatesToAsyncOutput()
- throws Exception {
- ListenableFuture<Foo> immediate = Futures.immediateFuture(new Foo());
- final SettableFuture<Bar> secondary = SettableFuture.create();
- AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
- @Override public ListenableFuture<Bar> apply(Foo unused) {
- return secondary;
- }
- };
- assertTrue(Futures.transform(immediate, function).cancel(true));
- assertTrue(secondary.isCancelled());
- assertTrue(secondary.wasInterrupted());
- }
-
/**
* {@link ListenableFuture} variant of
* {@link #testTransformValueRemainsMemoized_Future()}.
@@ -463,28 +382,6 @@ public class FuturesTest extends TestCase {
assertEquals(2, spy.getApplyCount());
}
- public void testLazyTransform_exception() throws Exception {
- final RuntimeException exception = new RuntimeException("deliberate");
- Function<Integer, String> function = new Function<Integer, String>() {
- @Override public String apply(Integer input) {
- throw exception;
- }
- };
- Future<String> transformed = Futures.lazyTransform(Futures.immediateFuture(1), function);
- try {
- transformed.get();
- fail();
- } catch (ExecutionException expected) {
- assertSame(exception, expected.getCause());
- }
- try {
- transformed.get(1, TimeUnit.SECONDS);
- fail();
- } catch (ExecutionException expected) {
- assertSame(exception, expected.getCause());
- }
- }
-
private static class FunctionSpy<I, O> implements Function<I, O> {
private int applyCount;
private final Function<I, O> delegate;
@@ -504,150 +401,6 @@ public class FuturesTest extends TestCase {
}
}
- @SuppressWarnings("unchecked")
- public void testWithFallback_inputDoesNotRaiseException() throws Exception {
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
- ListenableFuture<Integer> originalFuture = Futures.immediateFuture(7);
-
- mocksControl.replay();
- ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(originalFuture, fallback);
- assertEquals(7, faultToleranteFuture.get().intValue());
- mocksControl.verify();
- }
-
- @SuppressWarnings("unchecked")
- public void testWithFallback_inputRaisesException() throws Exception {
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
- RuntimeException raisedException = new RuntimeException();
- expect(fallback.create(raisedException)).andReturn(Futures.immediateFuture(20));
- ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
-
- mocksControl.replay();
- ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(failingFuture, fallback);
- assertEquals(20, faultToleranteFuture.get().intValue());
- mocksControl.verify();
- }
-
- public void testWithFallback_fallbackGeneratesRuntimeException() throws Exception {
- RuntimeException expectedException = new RuntimeException();
- runExpectedExceptionFallbackTest(expectedException, false);
- }
-
- public void testWithFallback_fallbackGeneratesCheckedException() throws Exception {
- Exception expectedException = new Exception() {};
- runExpectedExceptionFallbackTest(expectedException, false);
- }
-
- @SuppressWarnings("unchecked")
- public void testWithFallback_fallbackGeneratesError() throws Exception {
- Error error = new Error("deliberate");
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
- RuntimeException raisedException = new RuntimeException();
- expect(fallback.create(raisedException)).andThrow(error);
- ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
- mocksControl.replay();
- try {
- Futures.withFallback(failingFuture, fallback);
- fail("An Exception should have been thrown!");
- } catch (Error expected) {
- assertSame(error, expected);
- }
- mocksControl.verify();
- }
-
- public void testWithFallback_fallbackReturnsRuntimeException() throws Exception {
- RuntimeException expectedException = new RuntimeException();
- runExpectedExceptionFallbackTest(expectedException, true);
- }
-
- public void testWithFallback_fallbackReturnsCheckedException() throws Exception {
- Exception expectedException = new Exception() {};
- runExpectedExceptionFallbackTest(expectedException, true);
- }
-
- @SuppressWarnings("unchecked")
- private void runExpectedExceptionFallbackTest(
- Throwable expectedException, boolean wrapInFuture) throws Exception {
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
- RuntimeException raisedException = new RuntimeException();
- if (!wrapInFuture) {
- // Exception is thrown in the body of the "fallback" method.
- expect(fallback.create(raisedException)).andThrow(expectedException);
- } else {
- // Exception is wrapped in a future and returned.
- expect(fallback.create(raisedException)).andReturn(
- Futures.<Integer>immediateFailedFuture(expectedException));
- }
-
- ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
-
- mocksControl.replay();
- ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(failingFuture, fallback);
- try {
- faultToleranteFuture.get();
- fail("An Exception should have been thrown!");
- } catch (ExecutionException ee) {
- assertSame(expectedException, ee.getCause());
- }
- mocksControl.verify();
- }
-
- public void testWithFallback_fallbackNotReady() throws Exception {
- ListenableFuture<Integer> primary = immediateFailedFuture(new Exception());
- final SettableFuture<Integer> secondary = SettableFuture.create();
- FutureFallback<Integer> fallback = new FutureFallback<Integer>() {
- @Override
- public ListenableFuture<Integer> create(Throwable t) {
- return secondary;
- }
- };
- ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
- secondary.set(1);
- assertEquals(1, (int) derived.get());
- }
-
- @SuppressWarnings("unchecked")
- public void testWithFallback_resultInterruptedBeforeFallback() throws Exception {
- SettableFuture<Integer> primary = SettableFuture.create();
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
-
- mocksControl.replay();
- ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
- derived.cancel(true);
- assertTrue(primary.isCancelled());
- assertTrue(primary.wasInterrupted());
- mocksControl.verify();
- }
-
- @SuppressWarnings("unchecked")
- public void testWithFallback_resultCancelledBeforeFallback() throws Exception {
- SettableFuture<Integer> primary = SettableFuture.create();
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
-
- mocksControl.replay();
- ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
- derived.cancel(false);
- assertTrue(primary.isCancelled());
- assertFalse(primary.wasInterrupted());
- mocksControl.verify();
- }
-
- @SuppressWarnings("unchecked")
- public void testWithFallback_resultCancelledAfterFallback() throws Exception {
- SettableFuture<Integer> secondary = SettableFuture.create();
- FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
- RuntimeException raisedException = new RuntimeException();
- expect(fallback.create(raisedException)).andReturn(secondary);
- ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
-
- mocksControl.replay();
- ListenableFuture<Integer> derived = Futures.withFallback(failingFuture, fallback);
- derived.cancel(false);
- assertTrue(secondary.isCancelled());
- assertFalse(secondary.wasInterrupted());
- mocksControl.verify();
- }
-
public void testTransform_genericsWildcard_AsyncFunction() throws Exception {
ListenableFuture<?> nullFuture = Futures.immediateFuture(null);
ListenableFuture<?> chainedFuture =
@@ -680,108 +433,74 @@ public class FuturesTest extends TestCase {
assertSame(barChild, bar);
}
- public void testTransform_asyncFunction_timeout()
- throws InterruptedException, ExecutionException {
- AsyncFunction<String, Integer> function = constantAsyncFunction(Futures.immediateFuture(1));
- ListenableFuture<Integer> future = Futures.transform(
- SettableFuture.<String>create(), function);
- try {
- future.get(1, TimeUnit.MILLISECONDS);
- fail();
- } catch (TimeoutException expected) {}
+ public void testTransform_delegatesBlockingGet_AsyncFunction() throws Exception {
+ performAsyncFunctionTransformedFutureDelgationTest(0, null);
}
- public void testTransform_asyncFunction_error() {
- final Error error = new Error("deliberate");
- AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
- @Override public ListenableFuture<Integer> apply(String input) {
- throw error;
- }
- };
- SettableFuture<String> inputFuture = SettableFuture.create();
- Futures.transform(inputFuture, function);
- try {
- inputFuture.set("value");
- } catch (Error expected) {
- assertSame(error, expected);
- return;
- }
- fail("should have thrown error");
- }
-
- public void testTransform_asyncFunction_cancelledWhileApplyingFunction()
- throws InterruptedException, ExecutionException {
- final CountDownLatch inFunction = new CountDownLatch(1);
- final CountDownLatch functionDone = new CountDownLatch(1);
- final SettableFuture<Integer> resultFuture = SettableFuture.create();
- AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
- @Override public ListenableFuture<Integer> apply(String input) throws Exception {
- inFunction.countDown();
- functionDone.await();
- return resultFuture;
- }
- };
- SettableFuture<String> inputFuture = SettableFuture.create();
- ListenableFuture<Integer> future = Futures.transform(
- inputFuture, function, Executors.newSingleThreadExecutor());
- inputFuture.set("value");
- inFunction.await();
- future.cancel(false);
- functionDone.countDown();
- try {
- future.get();
- fail();
- } catch (CancellationException expected) {}
- try {
- resultFuture.get();
- fail();
- } catch (CancellationException expected) {}
+ public void testTransform_delegatesTimedGet_AsyncFunction() throws Exception {
+ performAsyncFunctionTransformedFutureDelgationTest(25, TimeUnit.SECONDS);
}
- public void testDereference_genericsWildcard() throws Exception {
- ListenableFuture<?> inner = Futures.immediateFuture(null);
- ListenableFuture<ListenableFuture<?>> outer =
- Futures.<ListenableFuture<?>>immediateFuture(inner);
- ListenableFuture<?> dereferenced = Futures.dereference(outer);
- assertNull(dereferenced.get());
- }
+ private void performAsyncFunctionTransformedFutureDelgationTest(
+ long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ final Foo foo = new Foo();
+ MockRequiresGetCallFuture<Foo> fooFuture =
+ new MockRequiresGetCallFuture<Foo>(foo);
+
+ Bar bar = new Bar();
+ final MockRequiresGetCallFuture<Bar> barFuture =
+ new MockRequiresGetCallFuture<Bar>(bar);
+ AsyncFunction<Foo, Bar> function =
+ new AsyncFunction<Foo, Bar>() {
+ @Override public ListenableFuture<Bar> apply(Foo from) {
+ assertSame(foo, from);
+ return barFuture;
+ }
+ };
- public void testDereference_genericsHierarchy() throws Exception {
- FooChild fooChild = new FooChild();
- ListenableFuture<FooChild> inner = Futures.immediateFuture(fooChild);
- ListenableFuture<ListenableFuture<FooChild>> outer = Futures.immediateFuture(inner);
- ListenableFuture<Foo> dereferenced = Futures.<Foo>dereference(outer);
- assertSame(fooChild, dereferenced.get());
+ ListenableFuture<Bar> chainFuture = Futures.transform(fooFuture, function);
+ Bar theBar;
+ if (unit != null) {
+ theBar = chainFuture.get(timeout, unit);
+ } else {
+ theBar = chainFuture.get();
+ }
+ assertSame(bar, theBar);
+ assertTrue(fooFuture.getWasGetCalled());
+ assertTrue(barFuture.getWasGetCalled());
}
- public void testDereference_resultCancelsOuter() throws Exception {
- ListenableFuture<ListenableFuture<Foo>> outer = SettableFuture.create();
- ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
- dereferenced.cancel(true);
- assertTrue(outer.isCancelled());
- }
+ /**
+ * A mock listenable future that requires the caller invoke
+ * either form of get() before the future will make its value
+ * available or invoke listeners.
+ */
+ private static class MockRequiresGetCallFuture<T> extends AbstractFuture<T> {
- public void testDereference_resultCancelsInner() throws Exception {
- ListenableFuture<Foo> inner = SettableFuture.create();
- ListenableFuture<ListenableFuture<Foo>> outer = Futures.immediateFuture(inner);
- ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
- dereferenced.cancel(true);
- assertTrue(inner.isCancelled());
- }
+ private final T value;
+ private boolean getWasCalled;
- public void testDereference_outerCancelsResult() throws Exception {
- ListenableFuture<ListenableFuture<Foo>> outer = SettableFuture.create();
- ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
- outer.cancel(true);
- assertTrue(dereferenced.isCancelled());
- }
+ MockRequiresGetCallFuture(T value) {
+ this.value = value;
+ }
- public void testDereference_innerCancelsResult() throws Exception {
- ListenableFuture<Foo> inner = SettableFuture.create();
- ListenableFuture<ListenableFuture<Foo>> outer = Futures.immediateFuture(inner);
- ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
- inner.cancel(true);
- assertTrue(dereferenced.isCancelled());
+ @Override public T get() throws InterruptedException, ExecutionException {
+ set(value);
+ getWasCalled = true;
+ return super.get();
+ }
+
+ @Override public T get(long timeout, TimeUnit unit)
+ throws TimeoutException, ExecutionException, InterruptedException {
+ set(value);
+ getWasCalled = true;
+ return super.get(timeout, unit);
+ }
+
+ boolean getWasGetCalled() {
+ return getWasCalled;
+ }
}
/**
@@ -840,7 +559,7 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(DATA1, DATA2, DATA3).inOrder();
+ ASSERT.that(results).hasContentsInOrder(DATA1, DATA2, DATA3);
}
public void testAllAsList_emptyList() throws Exception {
@@ -916,27 +635,6 @@ public class FuturesTest extends TestCase {
}
}
- public void testAllAsList_error() throws Exception {
- Error error = new Error("deliberate");
- SettableFuture<String> future1 = SettableFuture.create();
- ListenableFuture<String> future2 = Futures.immediateFuture("results");
- ListenableFuture<List<String>> compound = Futures.allAsList(ImmutableList.of(future1, future2));
-
- try {
- future1.setException(error);
- } catch (Error expected) {
- assertSame(error, expected);
- try {
- compound.get();
- } catch (ExecutionException ee) {
- assertSame(error, ee.getCause());
- return;
- }
- fail("Expected error not set in compound future.");
- }
- fail("Expected error not thrown");
- }
-
public void testAllAsList_cancelled() throws Exception {
SingleCallListener listener = new SingleCallListener();
SettableFuture<String> future1 = SettableFuture.create();
@@ -960,34 +658,22 @@ public class FuturesTest extends TestCase {
}
}
- public void testAllAsList_resultCancelled() throws Exception {
- SettableFuture<String> future1 = SettableFuture.create();
- SettableFuture<String> future2 = SettableFuture.create();
- @SuppressWarnings("unchecked") // array is never modified
- ListenableFuture<List<String>> compound =
- Futures.allAsList(future1, future2);
-
- future2.set(DATA2);
- assertFalse(compound.isDone());
- assertTrue(compound.cancel(false));
- assertTrue(compound.isCancelled());
- assertTrue(future1.isCancelled());
- assertFalse(future1.wasInterrupted());
- }
+ public void testAllAsList_buggyInputFutures() throws Exception {
+ final Foo foo1 = new Foo();
+ MockRequiresGetCallFuture<Foo> foo1Future =
+ new MockRequiresGetCallFuture<Foo>(foo1);
+ final Foo foo2 = new Foo();
+ MockRequiresGetCallFuture<Foo> foo2Future =
+ new MockRequiresGetCallFuture<Foo>(foo2);
- public void testAllAsList_resultInterrupted() throws Exception {
- SettableFuture<String> future1 = SettableFuture.create();
- SettableFuture<String> future2 = SettableFuture.create();
@SuppressWarnings("unchecked") // array is never modified
- ListenableFuture<List<String>> compound =
- Futures.allAsList(future1, future2);
+ ListenableFuture<List<Foo>> compound =
+ Futures.allAsList(foo1Future, foo2Future);
- future2.set(DATA2);
assertFalse(compound.isDone());
- assertTrue(compound.cancel(true));
- assertTrue(compound.isCancelled());
- assertTrue(future1.isCancelled());
- assertTrue(future1.wasInterrupted());
+ ASSERT.that(compound.get()).hasContentsAnyOrder(foo1, foo2);
+ assertTrue(foo1Future.getWasGetCalled());
+ assertTrue(foo2Future.getWasGetCalled());
}
/**
@@ -1021,10 +707,10 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(DATA1, DATA2, DATA3).inOrder();
+ ASSERT.that(results).hasContentsInOrder(DATA1, DATA2, DATA3);
}
- private static String createCombinedResult(Integer i, Boolean b) {
+ private String createCombinedResult(Integer i, Boolean b) {
return "-" + i + "-" + b;
}
@@ -1441,7 +1127,7 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(DATA1, DATA2, DATA3).inOrder();
+ ASSERT.that(results).hasContentsInOrder(DATA1, DATA2, DATA3);
}
public void testSuccessfulAsList_emptyList() throws Exception {
@@ -1484,7 +1170,7 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(null, DATA2).inOrder();
+ ASSERT.that(results).hasContentsInOrder(null, DATA2);
}
public void testSuccessfulAsList_totalFailure() throws Exception {
@@ -1505,7 +1191,7 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(null, null).inOrder();
+ ASSERT.that(results).hasContentsInOrder(null, null);
}
public void testSuccessfulAsList_cancelled() throws Exception {
@@ -1526,108 +1212,7 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(null, DATA2).inOrder();
- }
-
- public void testSuccessfulAsList_resultCancelled() throws Exception {
- SettableFuture<String> future1 = SettableFuture.create();
- SettableFuture<String> future2 = SettableFuture.create();
- @SuppressWarnings("unchecked") // array is never modified
- ListenableFuture<List<String>> compound =
- Futures.successfulAsList(future1, future2);
-
- future2.set(DATA2);
- assertFalse(compound.isDone());
- assertTrue(compound.cancel(false));
- assertTrue(compound.isCancelled());
- assertTrue(future1.isCancelled());
- assertFalse(future1.wasInterrupted());
- }
-
- public void testSuccessfulAsList_resultCancelledRacingInputDone()
- throws Exception {
- /*
- * The IllegalStateException that we're testing for is caught by
- * ExecutionList and logged rather than allowed to propagate. We need to
- * turn that back into a failure.
- */
- Handler throwingHandler = new Handler() {
- @Override public void publish(@Nullable LogRecord record) {
- AssertionFailedError error = new AssertionFailedError();
- error.initCause(record.getThrown());
- throw error;
- }
-
- @Override public void flush() {}
-
- @Override public void close() {}
- };
-
- ExecutionList.log.addHandler(throwingHandler);
- try {
- doTestSuccessfulAsList_resultCancelledRacingInputDone();
- } finally {
- ExecutionList.log.removeHandler(throwingHandler);
- }
- }
-
- private static void doTestSuccessfulAsList_resultCancelledRacingInputDone()
- throws Exception {
- // Simple (combined.cancel -> input.cancel -> setOneValue):
- Futures.successfulAsList(ImmutableList.of(SettableFuture.create()))
- .cancel(true);
-
- /*
- * Complex (combined.cancel -> input.cancel -> other.set -> setOneValue),
- * to show that this isn't just about problems with the input future we just
- * cancelled:
- */
- final SettableFuture<String> future1 = SettableFuture.create();
- final SettableFuture<String> future2 = SettableFuture.create();
- @SuppressWarnings("unchecked") // array is never modified
- ListenableFuture<List<String>> compound =
- Futures.successfulAsList(future1, future2);
-
- future1.addListener(new Runnable() {
- @Override public void run() {
- assertTrue(future1.isCancelled());
- /*
- * This test relies on behavior that's unspecified but currently
- * guaranteed by the implementation: Cancellation of inputs is
- * performed in the order they were provided to the constructor. Verify
- * that as a sanity check:
- */
- assertFalse(future2.isCancelled());
- // Now attempt to trigger the exception:
- future2.set(DATA2);
- }
- }, sameThreadExecutor());
- assertTrue(compound.cancel(false));
- assertTrue(compound.isCancelled());
- assertTrue(future1.isCancelled());
- assertFalse(future2.isCancelled());
-
- try {
- compound.get();
- fail("Expected exception not thrown");
- } catch (CancellationException e) {
- // Expected
- }
- }
-
- public void testSuccessfulAsList_resultInterrupted() throws Exception {
- SettableFuture<String> future1 = SettableFuture.create();
- SettableFuture<String> future2 = SettableFuture.create();
- @SuppressWarnings("unchecked") // array is never modified
- ListenableFuture<List<String>> compound =
- Futures.successfulAsList(future1, future2);
-
- future2.set(DATA2);
- assertFalse(compound.isDone());
- assertTrue(compound.cancel(true));
- assertTrue(compound.isCancelled());
- assertTrue(future1.isCancelled());
- assertTrue(future1.wasInterrupted());
+ ASSERT.that(results).hasContentsInOrder(null, DATA2);
}
public void testSuccessfulAsList_mixed() throws Exception {
@@ -1652,7 +1237,25 @@ public class FuturesTest extends TestCase {
assertTrue(listener.wasCalled());
List<String> results = compound.get();
- ASSERT.that(results).has().allOf(null, null, DATA3).inOrder();
+ ASSERT.that(results).hasContentsInOrder(null, null, DATA3);
+ }
+
+ public void testSuccessfulAsList_buggyInputFutures() throws Exception {
+ final Foo foo1 = new Foo();
+ MockRequiresGetCallFuture<Foo> foo1Future =
+ new MockRequiresGetCallFuture<Foo>(foo1);
+ final Foo foo2 = new Foo();
+ MockRequiresGetCallFuture<Foo> foo2Future =
+ new MockRequiresGetCallFuture<Foo>(foo2);
+
+ @SuppressWarnings("unchecked") // array is never modified
+ ListenableFuture<List<Foo>> compound =
+ Futures.successfulAsList(foo1Future, foo2Future);
+
+ assertFalse(compound.isDone());
+ ASSERT.that(compound.get()).hasContentsAnyOrder(foo1, foo2);
+ assertTrue(foo1Future.getWasGetCalled());
+ assertTrue(foo2Future.getWasGetCalled());
}
private static class TestException extends Exception {
@@ -1882,8 +1485,20 @@ public class FuturesTest extends TestCase {
private static final Future<String> FAILED_FUTURE_OTHER_THROWABLE =
immediateFailedFuture(OTHER_THROWABLE);
private static final Error ERROR = new Error("mymessage");
- private static final Future<String> FAILED_FUTURE_ERROR =
- immediateFailedFuture(ERROR);
+ private static final Future<String> FAILED_FUTURE_ERROR;
+ /*
+ * We can't write "= immediateFailedFuture(ERROR)" because setException
+ * rethrows the error....
+ */
+ static {
+ SettableFuture<String> f = SettableFuture.create();
+ try {
+ f.setException(ERROR);
+ } catch (Error e) {
+ assertEquals(e, ERROR);
+ }
+ FAILED_FUTURE_ERROR = f;
+ }
private static final Future<String> RUNTIME_EXCEPTION_FUTURE =
new SimpleForwardingFuture<String>(FAILED_FUTURE_CHECKED_EXCEPTION) {
@Override public String get() {
@@ -1904,10 +1519,9 @@ public class FuturesTest extends TestCase {
}
public void testGetUntimed_interrupted() {
- SettableFuture<String> future = SettableFuture.create();
Thread.currentThread().interrupt();
try {
- get(future, TwoArgConstructorException.class);
+ get(immediateFuture("foo"), TwoArgConstructorException.class);
fail();
} catch (TwoArgConstructorException expected) {
assertTrue(expected.getCause() instanceof InterruptedException);
@@ -1976,24 +1590,6 @@ public class FuturesTest extends TestCase {
}
}
- public void testGetUntimed_badExceptionConstructor_wrapsOriginalChecked() throws Exception {
- try {
- get(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithBadConstructor.class);
- fail();
- } catch (IllegalArgumentException expected) {
- assertSame(CHECKED_EXCEPTION, expected.getCause());
- }
- }
-
- public void testGetUntimed_withGoodAndBadExceptionConstructor() throws Exception {
- try {
- get(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithGoodAndBadConstructor.class);
- fail();
- } catch (ExceptionWithGoodAndBadConstructor expected) {
- assertSame(CHECKED_EXCEPTION, expected.getCause());
- }
- }
-
// Boring timed-get tests:
public void testGetTimed_success()
@@ -2003,10 +1599,9 @@ public class FuturesTest extends TestCase {
}
public void testGetTimed_interrupted() {
- SettableFuture<String> future = SettableFuture.create();
Thread.currentThread().interrupt();
try {
- get(future, 0, SECONDS, TwoArgConstructorException.class);
+ get(immediateFuture("foo"), 0, SECONDS, TwoArgConstructorException.class);
fail();
} catch (TwoArgConstructorException expected) {
assertTrue(expected.getCause() instanceof InterruptedException);
@@ -2089,25 +1684,6 @@ public class FuturesTest extends TestCase {
}
}
- public void testGetTimed_badExceptionConstructor_wrapsOriginalChecked() throws Exception {
- try {
- get(FAILED_FUTURE_CHECKED_EXCEPTION, 1, TimeUnit.SECONDS, ExceptionWithBadConstructor.class);
- fail();
- } catch (IllegalArgumentException expected) {
- assertSame(CHECKED_EXCEPTION, expected.getCause());
- }
- }
-
- public void testGetTimed_withGoodAndBadExceptionConstructor() throws Exception {
- try {
- get(FAILED_FUTURE_CHECKED_EXCEPTION, 1, TimeUnit.SECONDS,
- ExceptionWithGoodAndBadConstructor.class);
- fail();
- } catch (ExceptionWithGoodAndBadConstructor expected) {
- assertSame(CHECKED_EXCEPTION, expected.getCause());
- }
- }
-
// Boring getUnchecked tests:
public void testGetUnchecked_success() {
@@ -2331,26 +1907,31 @@ public class FuturesTest extends TestCase {
}
}
- private static final class ExceptionWithGoodAndBadConstructor extends Exception {
- public ExceptionWithGoodAndBadConstructor(String message, Throwable cause) {
- throw new RuntimeException("bad constructor");
- }
- public ExceptionWithGoodAndBadConstructor(Throwable cause) {
- super(cause);
- }
- }
+ public void testNullArguments() throws Exception {
+ NullPointerTester tester = new NullPointerTester();
+ tester.setDefault(ListenableFuture.class, Futures.immediateFuture(DATA1));
+ tester.setDefault(ListenableFuture[].class,
+ new ListenableFuture[] {Futures.immediateFuture(DATA1)});
+ tester.setDefault(Future.class, Futures.immediateFuture(DATA1));
+ tester.setDefault(Executor.class, MoreExecutors.sameThreadExecutor());
+ tester.setDefault(Callable.class, Callables.returning(null));
+ tester.setDefault(AsyncFunction.class, new AsyncFunction() {
+ @Override
+ public ListenableFuture apply(Object input) throws Exception {
+ return immediateFuture(DATA1);
+ }
+ });
- private static final class ExceptionWithBadConstructor extends Exception {
- public ExceptionWithBadConstructor(String message, Throwable cause) {
- throw new RuntimeException("bad constructor");
- }
- }
+ FutureCallback<Object> callback =
+ new FutureCallback<Object>() {
+ @Override
+ public void onSuccess(Object result) {}
+ @Override
+ public void onFailure(Throwable t) {}
+ };
+ tester.setDefault(FutureCallback.class, callback);
- public void testFutures_nullChecks() throws Exception {
- new ClassSanityTester()
- .forAllPublicStaticMethods(Futures.class)
- .thatReturn(Future.class)
- .testNulls();
+ tester.testAllPublicStaticMethods(Futures.class);
}
private static void failWithCause(Throwable cause, String message) {
diff --git a/guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java b/guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java
index 50d1be0..e610b20 100644
--- a/guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java
+++ b/guava-tests/test/com/google/common/util/concurrent/InterruptionUtil.java
@@ -16,7 +16,6 @@
package com.google.common.util.concurrent;
-import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static junit.framework.Assert.fail;
@@ -74,7 +73,6 @@ final class InterruptionUtil {
* Interrupts the current thread after sleeping for the specified delay.
*/
static void requestInterruptIn(final long time, final TimeUnit unit) {
- checkNotNull(unit);
final Thread interruptee = Thread.currentThread();
new Thread(new Runnable() {
@Override
diff --git a/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java b/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
index 23fc1e8..80b9599 100644
--- a/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
+++ b/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
@@ -15,22 +15,11 @@
package com.google.common.util.concurrent;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import static java.util.concurrent.TimeUnit.NANOSECONDS;
-
import junit.framework.*;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import java.security.CodeSource;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-import java.security.Policy;
-import java.security.ProtectionDomain;
-import java.security.SecurityPermission;
import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
@@ -38,6 +27,15 @@ import java.util.PropertyPermission;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import java.security.CodeSource;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.Policy;
+import java.security.ProtectionDomain;
+import java.security.SecurityPermission;
/**
* Base class for JSR166 Junit TCK tests. Defines some constants,
diff --git a/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java b/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java
index ab072eb..298733f 100644
--- a/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java
@@ -23,7 +23,7 @@ import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
-import com.google.common.testing.ClassSanityTester;
+import com.google.common.testing.NullPointerTester;
import com.google.common.util.concurrent.FuturesTest.ExecutorSpy;
import com.google.common.util.concurrent.FuturesTest.SingleCallListener;
@@ -206,10 +206,9 @@ public class JdkFutureAdaptersTest extends TestCase {
assertTrue(lateListener.wasRun.await(1, SECONDS));
}
- public void testAdapters_nullChecks() throws Exception {
- new ClassSanityTester()
- .forAllPublicStaticMethods(JdkFutureAdapters.class)
- .thatReturn(Future.class)
- .testNulls();
+ public void testNullArguments() throws Exception {
+ NullPointerTester tester = new NullPointerTester();
+ tester.setDefault(Future.class, immediateFuture(DATA1));
+ tester.testAllPublicStaticMethods(JdkFutureAdapters.class);
}
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
index cb10fc8..367b95a 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java
@@ -16,7 +16,6 @@
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.assertFalse;
import static junit.framework.Assert.assertTrue;
@@ -29,8 +28,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import javax.annotation.Nullable;
-
/**
* Used to test listenable future implementations.
*
@@ -44,7 +41,7 @@ public class ListenableFutureTester {
public ListenableFutureTester(ListenableFuture<?> future) {
this.exec = Executors.newCachedThreadPool();
- this.future = checkNotNull(future);
+ this.future = future;
this.latch = new CountDownLatch(1);
}
@@ -64,7 +61,7 @@ public class ListenableFutureTester {
exec.shutdown();
}
- public void testCompletedFuture(@Nullable Object expectedValue)
+ public void testCompletedFuture(Object expectedValue)
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
@@ -91,7 +88,7 @@ public class ListenableFutureTester {
} catch (CancellationException expected) {}
}
- public void testFailedFuture(@Nullable String message)
+ public void testFailedFuture(String message)
throws InterruptedException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
diff --git a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
index a6f8d2e..99a6be3 100644
--- a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
@@ -14,54 +14,26 @@
* limitations under the License.
*/
-/*
- * Portions of this file are modified versions of
- * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30
- * which contained the following notice:
- *
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
package com.google.common.util.concurrent;
import static com.google.common.collect.Iterables.getOnlyElement;
-import static com.google.common.util.concurrent.MoreExecutors.invokeAnyImpl;
import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;
import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.truth0.Truth.ASSERT;
+import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.testing.ClassSanityTester;
-import com.google.common.util.concurrent.MoreExecutors.Application;
-import org.mockito.InOrder;
-import org.mockito.Mockito;
+import junit.framework.TestCase;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
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.ScheduledThreadPoolExecutor;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -70,11 +42,7 @@ import java.util.concurrent.atomic.AtomicReference;
*
* @author Kyle Littlefield (klittle)
*/
-public class MoreExecutorsTest extends JSR166TestCase {
-
- private static final Runnable EMPTY_RUNNABLE = new Runnable() {
- @Override public void run() {}
- };
+public class MoreExecutorsTest extends TestCase {
public void testSameThreadExecutorServiceInThreadExecution()
throws Exception {
@@ -234,21 +202,6 @@ public class MoreExecutorsTest extends JSR166TestCase {
throwableFromOtherThread.get());
}
- public void testSameThreadExecutor_shutdownNow() {
- ExecutorService executor = MoreExecutors.sameThreadExecutor();
- assertEquals(ImmutableList.of(), executor.shutdownNow());
- assertTrue(executor.isShutdown());
- }
-
- public void testExecuteAfterShutdown() {
- ExecutorService executor = MoreExecutors.sameThreadExecutor();
- executor.shutdown();
- try {
- executor.execute(EMPTY_RUNNABLE);
- fail();
- } catch (RejectedExecutionException expected) {}
- }
-
public void testListeningDecorator() throws Exception {
ListeningExecutorService service =
listeningDecorator(MoreExecutors.sameThreadExecutor());
@@ -269,88 +222,6 @@ public class MoreExecutorsTest extends JSR166TestCase {
*/
}
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAnyImpl_nullTasks() throws Exception {
- ListeningExecutorService e = sameThreadExecutor();
- try {
- invokeAnyImpl(e, null, false, 0);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAnyImpl_emptyTasks() throws Exception {
- ListeningExecutorService e = sameThreadExecutor();
- try {
- invokeAnyImpl(e, new ArrayList<Callable<String>>(), false, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAnyImpl_nullElement() throws Exception {
- ListeningExecutorService e = sameThreadExecutor();
- List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
- l.add(new Callable<Integer>() {
- @Override public Integer call() {
- throw new ArithmeticException("/ by zero");
- }
- });
- l.add(null);
- try {
- invokeAnyImpl(e, l, false, 0);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task in c completes
- */
- public void testInvokeAnyImpl_noTaskCompletes() throws Exception {
- ListeningExecutorService e = sameThreadExecutor();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- invokeAnyImpl(e, l, false, 0);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task in c if at least one completes
- */
- public void testInvokeAnyImpl() throws Exception {
- ListeningExecutorService e = sameThreadExecutor();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = invokeAnyImpl(e, l, false, 0);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
private static void assertListenerRunImmediately(ListenableFuture<?> future) {
CountingRunnable listener = new CountingRunnable();
future.addListener(listener, sameThreadExecutor());
@@ -365,109 +236,4 @@ public class MoreExecutorsTest extends JSR166TestCase {
count++;
}
}
-
- public void testAddDelayedShutdownHook_success() throws InterruptedException {
- TestApplication application = new TestApplication();
- ExecutorService service = mock(ExecutorService.class);
- application.addDelayedShutdownHook(service, 2, TimeUnit.SECONDS);
- verify(service, Mockito.never()).shutdown();
- application.shutdown();
- InOrder shutdownFirst = Mockito.inOrder(service);
- shutdownFirst.verify(service).shutdown();
- shutdownFirst.verify(service).awaitTermination(2, TimeUnit.SECONDS);
- }
-
- public void testAddDelayedShutdownHook_interrupted() throws InterruptedException {
- TestApplication application = new TestApplication();
- ExecutorService service = mock(ExecutorService.class);
- application.addDelayedShutdownHook(service, 2, TimeUnit.SECONDS);
- when(service.awaitTermination(2, TimeUnit.SECONDS)).thenThrow(new InterruptedException());
- application.shutdown();
- verify(service).shutdown();
- }
-
- public void testGetExitingExcutorService_executorSetToUseDaemonThreads() {
- TestApplication application = new TestApplication();
- ThreadPoolExecutor executor = new ThreadPoolExecutor(
- 1, 2, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1));
- assertNotNull(application.getExitingExecutorService(executor));
- assertTrue(executor.getThreadFactory().newThread(EMPTY_RUNNABLE).isDaemon());
- }
-
- public void testGetExitingExcutorService_executorDelegatesToOriginal() {
- TestApplication application = new TestApplication();
- ThreadPoolExecutor executor = mock(ThreadPoolExecutor.class);
- ThreadFactory threadFactory = mock(ThreadFactory.class);
- when(executor.getThreadFactory()).thenReturn(threadFactory);
- application.getExitingExecutorService(executor).execute(EMPTY_RUNNABLE);
- verify(executor).execute(EMPTY_RUNNABLE);
- }
-
- public void testGetExitingExcutorService_shutdownHookRegistered() throws InterruptedException {
- TestApplication application = new TestApplication();
- ThreadPoolExecutor executor = mock(ThreadPoolExecutor.class);
- ThreadFactory threadFactory = mock(ThreadFactory.class);
- when(executor.getThreadFactory()).thenReturn(threadFactory);
- application.getExitingExecutorService(executor);
- application.shutdown();
- verify(executor).shutdown();
- }
-
- public void testGetExitingScheduledExcutorService_executorSetToUseDaemonThreads() {
- TestApplication application = new TestApplication();
- ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
- assertNotNull(application.getExitingScheduledExecutorService(executor));
- assertTrue(executor.getThreadFactory().newThread(EMPTY_RUNNABLE).isDaemon());
- }
-
- public void testGetExitingScheduledExcutorService_executorDelegatesToOriginal() {
- TestApplication application = new TestApplication();
- ScheduledThreadPoolExecutor executor = mock(ScheduledThreadPoolExecutor.class);
- ThreadFactory threadFactory = mock(ThreadFactory.class);
- when(executor.getThreadFactory()).thenReturn(threadFactory);
- application.getExitingScheduledExecutorService(executor).execute(EMPTY_RUNNABLE);
- verify(executor).execute(EMPTY_RUNNABLE);
- }
-
- public void testGetScheduledExitingExcutorService_shutdownHookRegistered()
- throws InterruptedException {
- TestApplication application = new TestApplication();
- ScheduledThreadPoolExecutor executor = mock(ScheduledThreadPoolExecutor.class);
- ThreadFactory threadFactory = mock(ThreadFactory.class);
- when(executor.getThreadFactory()).thenReturn(threadFactory);
- application.getExitingScheduledExecutorService(executor);
- application.shutdown();
- verify(executor).shutdown();
- }
-
- public void testPlatformThreadFactory_default() {
- ThreadFactory factory = MoreExecutors.platformThreadFactory();
- assertNotNull(factory);
- // Executors#defaultThreadFactory() may return a new instance each time.
- assertEquals(factory.getClass(), Executors.defaultThreadFactory().getClass());
- }
-
- public void testExecutors_nullCheck() throws Exception {
- new ClassSanityTester()
- .forAllPublicStaticMethods(MoreExecutors.class)
- .thatReturn(Executor.class)
- .testNulls();
- }
-
- private static class TestApplication extends Application {
- private final List<Thread> hooks = Lists.newArrayList();
-
- @Override synchronized void addShutdownHook(Thread hook) {
- hooks.add(hook);
- }
-
- synchronized void shutdown() throws InterruptedException {
- for (Thread hook : hooks) {
- hook.start();
- }
- for (Thread hook : hooks) {
- hook.join();
- }
- }
- }
}
diff --git a/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java b/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java
deleted file mode 100644
index d4da81a..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2012 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 com.google.common.testing.AbstractPackageSanityTests;
-
-/**
- * Basic sanity tests for the entire package.
- *
- * @author Ben Yu
- */
-
-public class PackageSanityTests extends AbstractPackageSanityTests {}
diff --git a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java b/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
deleted file mode 100644
index 4768213..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java
+++ /dev/null
@@ -1,363 +0,0 @@
-/*
- * Copyright (C) 2012 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 com.google.common.collect.Lists;
-import com.google.common.testing.NullPointerTester;
-import com.google.common.testing.NullPointerTester.Visibility;
-
-import junit.framework.TestCase;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Tests for RateLimiter.
- *
- * @author Dimitris Andreou
- */
-public class RateLimiterTest extends TestCase {
- /**
- * The ticker gathers events and presents them as strings.
- * R0.6 means a delay of 0.6 seconds caused by the (R)ateLimiter
- * U1.0 means the (U)ser caused the ticker to sleep for a second.
- */
- private final FakeTicker ticker = new FakeTicker();
-
- public void testSimple() {
- RateLimiter limiter = RateLimiter.create(ticker, 5.0);
- limiter.acquire(); // R0.00, since it's the first request
- limiter.acquire(); // R0.20
- limiter.acquire(); // R0.20
- assertEvents("R0.00", "R0.20", "R0.20");
- }
-
- public void testImmediateTryAcquire() {
- RateLimiter r = RateLimiter.create(1);
- assertTrue("Unable to acquire initial permit", r.tryAcquire());
- assertFalse("Capable of acquiring secondary permit", r.tryAcquire());
- }
-
- public void testSimpleRateUpdate() {
- RateLimiter limiter = RateLimiter.create(5.0, 5, TimeUnit.SECONDS);
- assertEquals(5.0, limiter.getRate());
- limiter.setRate(10.0);
- assertEquals(10.0, limiter.getRate());
-
- try {
- limiter.setRate(0.0);
- fail();
- } catch (IllegalArgumentException ok) {}
- try {
- limiter.setRate(-10.0);
- fail();
- } catch (IllegalArgumentException ok) {}
- }
-
- public void testSimpleWithWait() {
- RateLimiter limiter = RateLimiter.create(ticker, 5.0);
- limiter.acquire(); // R0.00
- ticker.sleepMillis(200); // U0.20, we are ready for the next request...
- limiter.acquire(); // R0.00, ...which is granted immediately
- limiter.acquire(); // R0.20
- assertEvents("R0.00", "U0.20", "R0.00", "R0.20");
- }
-
- public void testOneSecondBurst() {
- RateLimiter limiter = RateLimiter.create(ticker, 5.0);
- ticker.sleepMillis(1000); // max capacity reached
- ticker.sleepMillis(1000); // this makes no difference
- limiter.acquire(1); // R0.00, since it's the first request
-
- limiter.acquire(1); // R0.00, from capacity
- limiter.acquire(3); // R0.00, from capacity
- limiter.acquire(1); // R0.00, concluding a burst of 5 permits
-
- limiter.acquire(); // R0.20, capacity exhausted
- assertEvents("U1.00", "U1.00",
- "R0.00", "R0.00", "R0.00", "R0.00", // first request and burst
- "R0.20");
- }
-
- public void testWarmUp() {
- RateLimiter limiter = RateLimiter.create(ticker, 2.0, 4000, TimeUnit.MILLISECONDS);
- for (int i = 0; i < 8; i++) {
- limiter.acquire(); // #1
- }
- ticker.sleepMillis(500); // #2: to repay for the last acquire
- ticker.sleepMillis(4000); // #3: becomes cold again
- for (int i = 0; i < 8; i++) {
- limiter.acquire(); // // #4
- }
- ticker.sleepMillis(500); // #5: to repay for the last acquire
- ticker.sleepMillis(2000); // #6: didn't get cold! It would take another 2 seconds to go cold
- for (int i = 0; i < 8; i++) {
- limiter.acquire(); // #7
- }
- assertEvents(
- "R0.00, R1.38, R1.13, R0.88, R0.63, R0.50, R0.50, R0.50", // #1
- "U0.50", // #2
- "U4.00", // #3
- "R0.00, R1.38, R1.13, R0.88, R0.63, R0.50, R0.50, R0.50", // #4
- "U0.50", // #5
- "U2.00", // #6
- "R0.00, R0.50, R0.50, R0.50, R0.50, R0.50, R0.50, R0.50"); // #7
- }
-
- public void testWarmUpAndUpdate() {
- RateLimiter limiter = RateLimiter.create(ticker, 2.0, 4000, TimeUnit.MILLISECONDS);
- for (int i = 0; i < 8; i++) {
- limiter.acquire(); // // #1
- }
- ticker.sleepMillis(4500); // #2: back to cold state (warmup period + repay last acquire)
- for (int i = 0; i < 3; i++) { // only three steps, we're somewhere in the warmup period
- limiter.acquire(); // #3
- }
-
- limiter.setRate(4.0); // double the rate!
- limiter.acquire(); // #4, we repay the debt of the last acquire (imposed by the old rate)
- for (int i = 0; i < 4; i++) {
- limiter.acquire(); // #5
- }
- ticker.sleepMillis(4250); // #6, back to cold state (warmup period + repay last acquire)
- for (int i = 0; i < 11; i++) {
- limiter.acquire(); // #7, showing off the warmup starting from totally cold
- }
-
- // make sure the areas (times) remain the same, while permits are different
- assertEvents(
- "R0.00, R1.38, R1.13, R0.88, R0.63, R0.50, R0.50, R0.50", // #1
- "U4.50", // #2
- "R0.00, R1.38, R1.13", // #3, after that the rate changes
- "R0.88", // #4, this is what the throttling would be with the old rate
- "R0.34, R0.28, R0.25, R0.25", // #5
- "U4.25", // #6
- "R0.00, R0.72, R0.66, R0.59, R0.53, R0.47, R0.41", // #7
- "R0.34, R0.28, R0.25, R0.25"); // #7 (cont.), note, this matches #5
- }
-
- public void testBursty() {
- RateLimiter limiter = RateLimiter.createBursty(ticker, 1.0, 10);
- ticker.sleepMillis(10000); // reach full capacity
- limiter.acquire(11); // all these are served in a burst (10 + 1 by borrowing from the future)
- limiter.acquire(1); // out of capacity, we have to wait
- limiter.acquire(1); // and wait
- ticker.sleepMillis(3000); // fill up 3 permits
- limiter.acquire(5); // we had 3 ready, thus we borrow 2 permits
- limiter.acquire(1); // this acquire() will also repay for the previous acquire()
- assertEvents(
- "U10.00",
- "R0.00", // 10 permits grabbed
- "R1.00", "R1.00", // 1 and 1
- "U3.00", "R0.00", // 5 grabbed
- "R3.00" // 1 grabbed
- );
- }
-
- public void testBurstyAndUpdate() {
- RateLimiter rateLimiter = RateLimiter.create(ticker, 1.0);
- rateLimiter.acquire(1); // no wait
- rateLimiter.acquire(1); // R1.00, to repay previous
-
- rateLimiter.setRate(2.0); // update the rate!
-
- rateLimiter.acquire(1); // R1.00, to repay previous (the previous was under the old rate!)
- rateLimiter.acquire(2); // R0.50, to repay previous (now the rate takes effect)
- rateLimiter.acquire(4); // R1.00, to repay previous
- rateLimiter.acquire(1); // R2.00, to repay previous
- assertEvents("R0.00", "R1.00", "R1.00", "R0.50", "R1.00", "R2.00");
- }
-
- public void testTimeWrapping() {
- ticker.instant = Long.MAX_VALUE - TimeUnit.SECONDS.toNanos(1); // 1 second before max value
- RateLimiter limiter = RateLimiter.create(ticker, 1.0);
- for (int i = 0; i < 4; i++) {
- limiter.acquire();
- }
- // Without protection from overflow, the last wait value would have been huge,
- // because "now" would have wrapped into a value near MIN_VALUE, and the limiter would think
- // that the next request should be admitted far into the future
- assertEvents("R0.00", "R1.00", "R1.00", "R1.00");
- }
-
- public void testTryGate() {
- RateLimiter limiter = RateLimiter.create(ticker, 5.0);
- assertTrue(limiter.tryAcquire(0, TimeUnit.SECONDS));
- assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS));
- assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS));
- ticker.sleepMillis(100);
- assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS));
- }
-
- public void testSimpleWeights() {
- RateLimiter rateLimiter = RateLimiter.create(ticker, 1.0);
- rateLimiter.acquire(1); // no wait
- rateLimiter.acquire(1); // R1.00, to repay previous
- rateLimiter.acquire(2); // R1.00, to repay previous
- rateLimiter.acquire(4); // R2.00, to repay previous
- rateLimiter.acquire(8); // R4.00, to repay previous
- rateLimiter.acquire(1); // R8.00, to repay previous
- assertEvents("R0.00", "R1.00", "R1.00", "R2.00", "R4.00", "R8.00");
- }
-
- public void testInfinity_Bursty() {
- RateLimiter limiter = RateLimiter.create(ticker, Double.POSITIVE_INFINITY);
- limiter.acquire(Integer.MAX_VALUE / 4);
- limiter.acquire(Integer.MAX_VALUE / 2);
- limiter.acquire(Integer.MAX_VALUE);
- assertEvents("R0.00", "R0.00", "R0.00"); // no wait, infinite rate!
-
- limiter.setRate(1.0);
- limiter.acquire();
- limiter.acquire();
- limiter.acquire();
- assertEvents("R0.00", "R1.00", "R1.00"); // we repay the last request (but that had no cost)
- // and then we go to 1 second per request mode
-
- limiter.setRate(Double.POSITIVE_INFINITY);
- limiter.acquire();
- limiter.acquire();
- limiter.acquire();
- assertEvents("R1.00", "R0.00", "R0.00"); // we repay the last request (1sec), then back to +oo
- }
-
- public void testInfinity_WarmUp() {
- RateLimiter limiter = RateLimiter.create(
- ticker, Double.POSITIVE_INFINITY, 10, TimeUnit.SECONDS);
- limiter.acquire(Integer.MAX_VALUE / 4);
- limiter.acquire(Integer.MAX_VALUE / 2);
- limiter.acquire(Integer.MAX_VALUE);
- assertEvents("R0.00", "R0.00", "R0.00");
-
- limiter.setRate(1.0);
- limiter.acquire();
- limiter.acquire();
- limiter.acquire();
- assertEvents("R0.00", "R1.00", "R1.00");
-
- limiter.setRate(Double.POSITIVE_INFINITY);
- limiter.acquire();
- limiter.acquire();
- limiter.acquire();
- assertEvents("R1.00", "R0.00", "R0.00");
- }
-
- /**
- * Make sure that bursts can never go above 1-second-worth-of-work for the current
- * rate, even when we change the rate.
- */
- public void testWeNeverGetABurstMoreThanOneSec() {
- RateLimiter limiter = RateLimiter.create(ticker, 1.0);
- int[] rates = { 1000, 1, 10, 1000000, 10, 1};
- for (int rate : rates) {
- int oneSecWorthOfWork = rate;
- ticker.sleepMillis(rate * 1000);
- limiter.setRate(rate);
- long burst = measureTotalTimeMillis(limiter, oneSecWorthOfWork, new Random());
- // we allow one second worth of work to go in a burst (i.e. take less than a second)
- assertTrue(burst <= 1000);
- long afterBurst = measureTotalTimeMillis(limiter, oneSecWorthOfWork, new Random());
- // but work beyond that must take at least one second
- assertTrue(afterBurst >= 1000);
- }
- }
-
- /**
- * This neat test shows that no matter what weights we use in our requests, if we push X
- * amount of permits in a cool state, where X = rate * timeToCoolDown, and we have
- * specified a timeToWarmUp() period, it will cost as the prescribed amount of time. E.g.,
- * calling [acquire(5), acquire(1)] takes exactly the same time as
- * [acquire(2), acquire(3), acquire(1)].
- */
- public void testTimeToWarmUpIsHonouredEvenWithWeights() {
- Random random = new Random();
- int maxPermits = 10;
- double[] qpsToTest = { 4.0, 2.0, 1.0, 0.5, 0.1 };
- for (int trial = 0; trial < 100; trial++) {
- for (double qps : qpsToTest) {
- // Since we know that: maxPermits = 0.5 * warmup / stableInterval;
- // then if maxPermits == 10, we have:
- // warmupSeconds = 20 / qps
- long warmupMillis = (long) ((2 * maxPermits / qps) * 1000.0);
- RateLimiter rateLimiter = RateLimiter.create(
- ticker, qps, warmupMillis, TimeUnit.MILLISECONDS);
- assertEquals(warmupMillis, measureTotalTimeMillis(rateLimiter, maxPermits, random));
- }
- }
- }
-
- public void testNulls() {
- NullPointerTester tester = new NullPointerTester()
- .setDefault(RateLimiter.SleepingTicker.class, ticker);
- tester.testStaticMethods(RateLimiter.class, Visibility.PACKAGE);
- tester.testInstanceMethods(RateLimiter.create(ticker, 5.0), Visibility.PACKAGE);
- }
-
- private long measureTotalTimeMillis(RateLimiter rateLimiter, int permits, Random random) {
- long startTime = ticker.instant;
- while (permits > 0) {
- int nextPermitsToAcquire = Math.max(1, random.nextInt(permits));
- permits -= nextPermitsToAcquire;
- rateLimiter.acquire(nextPermitsToAcquire);
- }
- rateLimiter.acquire(1); // to repay for any pending debt
- return TimeUnit.NANOSECONDS.toMillis(ticker.instant - startTime);
- }
-
- private void assertEvents(String... events) {
- assertEquals(Arrays.asList(events).toString(), ticker.readEventsAndClear());
- }
-
- private static class FakeTicker extends RateLimiter.SleepingTicker {
- long instant = 0L;
- final List<String> events = Lists.newArrayList();
-
- @Override
- public long read() {
- return instant;
- }
-
- void sleepMillis(int millis) {
- sleepMicros("U", TimeUnit.MILLISECONDS.toMicros(millis));
- }
-
- void sleepMicros(String caption, long micros) {
- instant += TimeUnit.MICROSECONDS.toNanos(micros);
- events.add(caption + String.format("%3.2f", (micros / 1000000.0)));
- }
-
- @Override
- void sleepMicrosUninterruptibly(long micros) {
- sleepMicros("R", micros);
- }
-
- String readEventsAndClear() {
- try {
- return events.toString();
- } finally {
- events.clear();
- }
- }
-
- @Override
- public String toString() {
- return events.toString();
- }
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java b/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
index 3651934..1db434a 100644
--- a/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java
@@ -183,7 +183,7 @@ public class SimpleTimeLimiterTest extends TestCase {
}
@SuppressWarnings("serial")
- public static class SampleException extends Exception {}
+ public static class SampleException extends Exception { }
public static class SampleImpl implements Sample {
boolean finished;
diff --git a/guava-tests/test/com/google/common/util/concurrent/StripedTest.java b/guava-tests/test/com/google/common/util/concurrent/StripedTest.java
deleted file mode 100644
index 0a4a655..0000000
--- a/guava-tests/test/com/google/common/util/concurrent/StripedTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2011 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.collect.Iterables.concat;
-
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Ordering;
-import com.google.common.collect.Sets;
-import com.google.common.testing.GcFinalization;
-import com.google.common.testing.NullPointerTester;
-
-import junit.framework.TestCase;
-
-import java.lang.ref.WeakReference;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-
-/**
- * Tests for Striped.
- *
- * @author Dimitris Andreou
- */
-public class StripedTest extends TestCase {
- private static List<Striped<?>> strongImplementations() {
- return ImmutableList.of(
- Striped.readWriteLock(100),
- Striped.readWriteLock(256),
- Striped.lock(100),
- Striped.lock(256),
- Striped.semaphore(100, 1),
- Striped.semaphore(256, 1));
- }
-
- private static List<Striped<?>> weakImplementations() {
- return ImmutableList.of(
- Striped.lazyWeakReadWriteLock(50),
- Striped.lazyWeakReadWriteLock(64),
- Striped.lazyWeakLock(50),
- Striped.lazyWeakLock(64),
- Striped.lazyWeakSemaphore(50, 1),
- Striped.lazyWeakSemaphore(64, 1));
- }
-
- private static Iterable<Striped<?>> allImplementations() {
- return concat(strongImplementations(), weakImplementations());
- }
-
- public void testNull() throws Exception {
- for (Striped<?> striped : allImplementations()) {
- new NullPointerTester().testAllPublicInstanceMethods(striped);
- }
- }
-
- public void testSizes() {
- // not bothering testing all variations, since we know they share implementations
- assertTrue(Striped.lock(100).size() >= 100);
- assertTrue(Striped.lock(256).size() == 256);
- assertTrue(Striped.lazyWeakLock(100).size() >= 100);
- assertTrue(Striped.lazyWeakLock(256).size() == 256);
- }
-
- public void testWeakImplementations() {
- for (Striped<?> striped : weakImplementations()) {
- WeakReference<Object> weakRef = new WeakReference<Object>(striped.get(new Object()));
- GcFinalization.awaitClear(weakRef);
- }
- }
-
- public void testStrongImplementations() {
- for (Striped<?> striped : strongImplementations()) {
- WeakReference<Object> weakRef = new WeakReference<Object>(striped.get(new Object()));
- WeakReference<Object> garbage = new WeakReference<Object>(new Object());
- GcFinalization.awaitClear(garbage);
- assertNotNull(weakRef.get());
- }
- }
-
- public void testMaximalWeakStripedLock() {
- Striped<Lock> stripedLock = Striped.lazyWeakLock(Integer.MAX_VALUE);
- for (int i = 0; i < 10000; i++) {
- stripedLock.get(new Object()).lock();
- // nothing special (e.g. an exception) happens
- }
- }
-
- public void testBulkGetReturnsSorted() {
- for (Striped<?> striped : allImplementations()) {
- Map<Object, Integer> indexByLock = Maps.newHashMap();
- for (int i = 0; i < striped.size(); i++) {
- indexByLock.put(striped.getAt(i), i);
- }
-
- // ensure that bulkGet returns locks in monotonically increasing order
- for (int objectsNum = 1; objectsNum <= striped.size() * 2; objectsNum++) {
- Set<Object> objects = Sets.newHashSetWithExpectedSize(objectsNum);
- for (int i = 0; i < objectsNum; i++) {
- objects.add(new Object());
- }
-
- Iterable<?> locks = striped.bulkGet(objects);
- assertTrue(Ordering.natural().onResultOf(Functions.forMap(indexByLock)).isOrdered(locks));
-
- // check idempotency
- Iterable<?> locks2 = striped.bulkGet(objects);
- assertEquals(Lists.newArrayList(locks), Lists.newArrayList(locks2));
- }
- }
- }
-
- /**
- * Checks idempotency, and that we observe the promised number of stripes.
- */
- public void testBasicInvariants() {
- for (Striped<?> striped : allImplementations()) {
- assertBasicInvariants(striped);
- }
- }
-
- private static void assertBasicInvariants(Striped<?> striped) {
- Set<Object> observed = Sets.newIdentityHashSet(); // for the sake of weakly referenced locks.
- // this gets the stripes with #getAt(index)
- for (int i = 0; i < striped.size(); i++) {
- Object object = striped.getAt(i);
- assertNotNull(object);
- assertSame(object, striped.getAt(i)); // idempotent
- observed.add(object);
- }
- assertTrue("All stripes observed", observed.size() == striped.size());
-
- // this uses #get(key), makes sure an already observed stripe is returned
- for (int i = 0; i < striped.size() * 100; i++) {
- assertTrue(observed.contains(striped.get(new Object())));
- }
-
- try {
- striped.getAt(-1);
- fail();
- } catch (RuntimeException expected) {}
-
- try {
- striped.getAt(striped.size());
- fail();
- } catch (RuntimeException expected) {}
- }
-}
diff --git a/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java b/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java
index d26ba63..ec850d3 100644
--- a/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java
+++ b/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java
@@ -16,7 +16,7 @@
package com.google.common.util.concurrent;
-import static org.truth0.Truth.ASSERT;
+import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.testing.NullPointerTester;
@@ -93,20 +93,11 @@ public class ThreadFactoryBuilderTest extends TestCase {
assertTrue(thread.getName().matches("^pool-\\d+-thread-" + threadId + "$"));
}
- public void testNameFormatWithPercentS_custom() {
- String format = "super-duper-thread-%s";
- ThreadFactory factory = builder.setNameFormat(format).build();
- for (int i = 0; i < 11; i++) {
- assertEquals(String.format(format, i),
- factory.newThread(monitoredRunnable).getName());
- }
- }
-
- public void testNameFormatWithPercentD_custom() {
- String format = "super-duper-thread-%d";
- ThreadFactory factory = builder.setNameFormat(format).build();
- for (int i = 0; i < 11; i++) {
- assertEquals(String.format(format, i),
+ public void testNameFormat_custom() {
+ final String NAME_FORMAT = "super duper thread #%s";
+ ThreadFactory factory = builder.setNameFormat(NAME_FORMAT).build();
+ for (int i = 0; i < 10; i++) {
+ assertEquals(String.format(NAME_FORMAT, i),
factory.newThread(monitoredRunnable).getName());
}
}
@@ -206,7 +197,7 @@ public class ThreadFactoryBuilderTest extends TestCase {
assertTrue(completed);
}
- public void testNulls() {
+ public void testNulls() throws Exception {
NullPointerTester npTester = new NullPointerTester();
npTester.testAllPublicConstructors(ThreadFactoryBuilder.class);
npTester.testAllPublicStaticMethods(ThreadFactoryBuilder.class);