Search in sources :

Example 11 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class ThriftTest method testDoCallDeadlineExpired.

@Test
@Ignore("Flaky: https://trac.twitter.com/twttr/ticket/11474")
public void testDoCallDeadlineExpired() throws Exception {
    TestService testService = expectServiceCall(true);
    // Setup a way to verify the callable was cancelled by Thrift when timeout elapsed
    final CountDownLatch remoteCallComplete = new CountDownLatch(1);
    final CountDownLatch remoteCallStarted = new CountDownLatch(1);
    final Command verifyCancelled = control.createMock(Command.class);
    verifyCancelled.execute();
    final Object block = new Object();
    expect(testService.calculateMass("jake")).andAnswer(new IAnswer<Integer>() {

        @Override
        public Integer answer() throws TException {
            try {
                synchronized (block) {
                    remoteCallStarted.countDown();
                    block.wait();
                }
                fail("Expected late work to be cancelled and interrupted");
            } catch (InterruptedException e) {
                verifyCancelled.execute();
            } finally {
                remoteCallComplete.countDown();
            }
            throw new TTransportException();
        }
    });
    requestTracker.requestResult((InetSocketAddress) anyObject(), eq(RequestTracker.RequestResult.TIMEOUT), anyLong());
    ExecutorService executorService = new ForwardingExecutorService<ExecutorService>(Executors.newSingleThreadExecutor()) {

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            Future<T> future = super.submit(task);
            // make sure the task is started so we can verify it gets cancelled
            try {
                remoteCallStarted.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return future;
        }
    };
    Thrift<TestService> thrift = createThrift(executorService);
    control.replay();
    try {
        thrift.builder().withRequestTimeout(Amount.of(1L, Time.NANOSECONDS)).create().calculateMass("jake");
        fail("Expected a timeout");
    } catch (TTimeoutException e) {
    // expected
    } finally {
        remoteCallComplete.await();
    }
    assertRequestsTotal(thrift, 0);
    assertErrorsTotal(thrift, 0);
    assertReconnectsTotal(thrift, 0);
    assertTimeoutsTotal(thrift, 1);
    control.verify();
}
Also used : TException(org.apache.thrift.TException) TTransportException(org.apache.thrift.transport.TTransportException) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) ForwardingExecutorService(com.twitter.common.util.concurrent.ForwardingExecutorService) Command(com.twitter.common.base.Command) ForwardingExecutorService(com.twitter.common.util.concurrent.ForwardingExecutorService) ExecutorService(java.util.concurrent.ExecutorService) EasyMock.anyObject(org.easymock.EasyMock.anyObject) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 12 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class StateMachineTest method testDoInStateConcurrently.

@Test
public void testDoInStateConcurrently() throws InterruptedException {
    control.replay();
    final StateMachine<String> stateMachine = StateMachine.<String>builder(NAME).initialState(A).addState(A, B).build();
    final BlockingQueue<Integer> results = new LinkedBlockingQueue<Integer>();
    final CountDownLatch supplier1Proceed = new CountDownLatch(1);
    final ExceptionalSupplier<Void, RuntimeException> supplier1 = Commands.asSupplier(new Command() {

        @Override
        public void execute() {
            results.offer(1);
            try {
                supplier1Proceed.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    });
    final CountDownLatch supplier2Proceed = new CountDownLatch(1);
    final ExceptionalSupplier<Void, RuntimeException> supplier2 = Commands.asSupplier(new Command() {

        @Override
        public void execute() {
            results.offer(2);
            try {
                supplier2Proceed.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    });
    Thread thread1 = new Thread(new Runnable() {

        @Override
        public void run() {
            stateMachine.doInState(A, supplier1);
        }
    });
    Thread thread2 = new Thread(new Runnable() {

        @Override
        public void run() {
            stateMachine.doInState(A, supplier2);
        }
    });
    Thread thread3 = new Thread(new Runnable() {

        @Override
        public void run() {
            stateMachine.transition(B);
        }
    });
    thread1.start();
    thread2.start();
    Integer result1 = results.take();
    Integer result2 = results.take();
    // we know 1 and 2 have the read lock held
    // should be blocked by read locks in place
    thread3.start();
    assertThat(ImmutableSet.of(result1, result2), is(ImmutableSet.of(1, 2)));
    assertTrue(results.isEmpty());
    supplier1Proceed.countDown();
    supplier2Proceed.countDown();
    thread1.join();
    thread2.join();
    thread3.join();
    assertThat(B, is(stateMachine.getState()));
}
Also used : LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Command(com.twitter.common.base.Command) EasyMockTest(com.twitter.common.testing.easymock.EasyMockTest) Test(org.junit.Test)

Example 13 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class ServerSetImplTest method testStopMonitoring.

@Test
public void testStopMonitoring() throws Exception {
    ServerSetImpl client = createServerSet();
    Command stopMonitoring = client.watch(serverSetMonitor);
    assertChangeFiredEmpty();
    ServerSetImpl server = createServerSet();
    EndpointStatus foo = join(server, "foo");
    assertChangeFired("foo");
    EndpointStatus bar = join(server, "bar");
    assertChangeFired("foo", "bar");
    stopMonitoring.execute();
    // No new updates should be received since monitoring has stopped.
    foo.leave();
    assertTrue(serverSetBuffer.isEmpty());
    // Expiration event.
    assertTrue(serverSetBuffer.isEmpty());
}
Also used : EndpointStatus(com.twitter.common.zookeeper.ServerSet.EndpointStatus) Command(com.twitter.common.base.Command) BaseZooKeeperTest(com.twitter.common.zookeeper.testing.BaseZooKeeperTest) Test(org.junit.Test)

Example 14 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class DynamicHostSetUtil method getSnapshot.

/**
   * Gets a snapshot of a set of dynamic hosts (e.g. a ServerSet) and returns a readable copy of
   * the underlying actual endpoints.
   *
   * @param hostSet The hostSet to snapshot.
   * @throws MonitorException if there was a problem obtaining the snapshot.
   */
public static <T> ImmutableSet<T> getSnapshot(DynamicHostSet<T> hostSet) throws MonitorException {
    final ImmutableSet.Builder<T> snapshot = ImmutableSet.builder();
    Command unwatch = hostSet.watch(new HostChangeMonitor<T>() {

        @Override
        public void onChange(ImmutableSet<T> hostSet) {
            snapshot.addAll(hostSet);
        }
    });
    unwatch.execute();
    return snapshot.build();
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Command(com.twitter.common.base.Command)

Example 15 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class MetaPool method startDeadBackendRestorer.

private Command startDeadBackendRestorer(final Amount<Long, Time> restoreInterval) {
    final AtomicBoolean shouldRestore = new AtomicBoolean(true);
    Runnable restoreDeadBackends = new Runnable() {

        @Override
        public void run() {
            if (shouldRestore.get()) {
                restoreDeadBackends(restoreInterval);
            }
        }
    };
    final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("MTCP-DeadBackendRestorer[%s]").build());
    long restoreDelay = restoreInterval.getValue();
    scheduledExecutorService.scheduleWithFixedDelay(restoreDeadBackends, restoreDelay, restoreDelay, restoreInterval.getUnit().getTimeUnit());
    return new Command() {

        @Override
        public void execute() {
            shouldRestore.set(false);
            scheduledExecutorService.shutdownNow();
            LOG.info("Backend restorer shut down");
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Command(com.twitter.common.base.Command) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder)

Aggregations

Command (com.twitter.common.base.Command)23 Test (org.junit.Test)15 EasyMockTest (com.twitter.common.testing.easymock.EasyMockTest)6 BaseZooKeeperTest (com.twitter.common.zookeeper.testing.BaseZooKeeperTest)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Membership (com.twitter.common.zookeeper.Group.Membership)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)2 AbstractModule (com.google.inject.AbstractModule)2 Injector (com.google.inject.Injector)2 Module (com.google.inject.Module)2 ShutdownRegistryImpl (com.twitter.common.application.ShutdownRegistry.ShutdownRegistryImpl)2 ExceptionalCommand (com.twitter.common.base.ExceptionalCommand)2 ZooKeeperConnectionException (com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 KeeperException (org.apache.zookeeper.KeeperException)2 Watcher (org.apache.zookeeper.Watcher)2 Supplier (com.google.common.base.Supplier)1