Search in sources :

Example 16 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project cdap by caskdata.

the class ResourceCoordinatorTest method testAssignment.

@Test
public void testAssignment() throws InterruptedException, ExecutionException {
    CConfiguration cConf = CConfiguration.create();
    cConf.set(Constants.Zookeeper.QUORUM, zkServer.getConnectionStr());
    String serviceName = "test-assignment";
    Injector injector = Guice.createInjector(new ConfigModule(cConf), new ZKClientModule(), new DiscoveryRuntimeModule().getDistributedModules());
    ZKClientService zkClient = injector.getInstance(ZKClientService.class);
    zkClient.startAndWait();
    DiscoveryService discoveryService = injector.getInstance(DiscoveryService.class);
    try {
        ResourceCoordinator coordinator = new ResourceCoordinator(zkClient, injector.getInstance(DiscoveryServiceClient.class), new BalancedAssignmentStrategy());
        coordinator.startAndWait();
        try {
            ResourceCoordinatorClient client = new ResourceCoordinatorClient(zkClient);
            client.startAndWait();
            try {
                // Create a requirement
                ResourceRequirement requirement = ResourceRequirement.builder(serviceName).addPartitions("p", 5, 1).build();
                client.submitRequirement(requirement).get();
                // Fetch the requirement, just to verify it's the same as the one get submitted.
                Assert.assertEquals(requirement, client.fetchRequirement(requirement.getName()).get());
                // Register a discovery endpoint
                final Discoverable discoverable1 = createDiscoverable(serviceName, 10000);
                Cancellable cancelDiscoverable1 = discoveryService.register(ResolvingDiscoverable.of(discoverable1));
                // Add a change handler for this discoverable.
                final BlockingQueue<Collection<PartitionReplica>> assignmentQueue = new SynchronousQueue<>();
                final Semaphore finishSemaphore = new Semaphore(0);
                Cancellable cancelSubscribe1 = subscribe(client, discoverable1, assignmentQueue, finishSemaphore);
                // Assert that it received the changes.
                Collection<PartitionReplica> assigned = assignmentQueue.poll(30, TimeUnit.SECONDS);
                Assert.assertNotNull(assigned);
                Assert.assertEquals(5, assigned.size());
                // Unregister from discovery, the handler should receive a change with empty collection
                cancelDiscoverable1.cancel();
                Assert.assertTrue(assignmentQueue.poll(30, TimeUnit.SECONDS).isEmpty());
                // Register to discovery again, would receive changes.
                cancelDiscoverable1 = discoveryService.register(ResolvingDiscoverable.of(discoverable1));
                assigned = assignmentQueue.poll(30, TimeUnit.SECONDS);
                Assert.assertNotNull(assigned);
                Assert.assertEquals(5, assigned.size());
                // Register another discoverable
                final Discoverable discoverable2 = createDiscoverable(serviceName, 10001);
                Cancellable cancelDiscoverable2 = discoveryService.register(ResolvingDiscoverable.of(discoverable2));
                // Changes should be received by the handler, with only 3 resources,
                // as 2 out of 5 should get moved to the new discoverable.
                assigned = assignmentQueue.poll(30, TimeUnit.SECONDS);
                Assert.assertNotNull(assigned);
                Assert.assertEquals(3, assigned.size());
                // Cancel the first discoverable again, should expect empty result.
                // This also make sure the latest assignment get cached in the ResourceCoordinatorClient.
                // It is the the next test step.
                cancelDiscoverable1.cancel();
                Assert.assertTrue(assignmentQueue.poll(30, TimeUnit.SECONDS).isEmpty());
                // Cancel the handler.
                cancelSubscribe1.cancel();
                Assert.assertTrue(finishSemaphore.tryAcquire(2, TimeUnit.SECONDS));
                // Subscribe to changes for the second discoverable,
                // it should see the latest assignment, even though no new fetch from ZK is triggered.
                Cancellable cancelSubscribe2 = subscribe(client, discoverable2, assignmentQueue, finishSemaphore);
                assigned = assignmentQueue.poll(30, TimeUnit.SECONDS);
                Assert.assertNotNull(assigned);
                Assert.assertEquals(5, assigned.size());
                // Update the requirement to be an empty requirement, the handler should receive an empty collection
                client.submitRequirement(ResourceRequirement.builder(serviceName).build());
                Assert.assertTrue(assignmentQueue.poll(30, TimeUnit.SECONDS).isEmpty());
                // Update the requirement to have one partition, the handler should receive one resource
                client.submitRequirement(ResourceRequirement.builder(serviceName).addPartitions("p", 1, 1).build());
                assigned = assignmentQueue.poll(30, TimeUnit.SECONDS);
                Assert.assertNotNull(assigned);
                Assert.assertEquals(1, assigned.size());
                // Delete the requirement, the handler should receive a empty collection
                client.deleteRequirement(requirement.getName());
                Assert.assertTrue(assignmentQueue.poll(30, TimeUnit.SECONDS).isEmpty());
                // Cancel the second handler.
                cancelSubscribe2.cancel();
                Assert.assertTrue(finishSemaphore.tryAcquire(2, TimeUnit.SECONDS));
                cancelDiscoverable2.cancel();
            } finally {
                client.stopAndWait();
            }
        } finally {
            coordinator.stopAndWait();
        }
    } finally {
        zkClient.stopAndWait();
    }
}
Also used : Discoverable(org.apache.twill.discovery.Discoverable) ResolvingDiscoverable(co.cask.cdap.common.discovery.ResolvingDiscoverable) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) ConfigModule(co.cask.cdap.common.guice.ConfigModule) Cancellable(org.apache.twill.common.Cancellable) Semaphore(java.util.concurrent.Semaphore) CConfiguration(co.cask.cdap.common.conf.CConfiguration) ZKClientModule(co.cask.cdap.common.guice.ZKClientModule) ZKClientService(org.apache.twill.zookeeper.ZKClientService) Injector(com.google.inject.Injector) SynchronousQueue(java.util.concurrent.SynchronousQueue) Collection(java.util.Collection) DiscoveryService(org.apache.twill.discovery.DiscoveryService) DiscoveryRuntimeModule(co.cask.cdap.common.guice.DiscoveryRuntimeModule) Test(org.junit.Test)

Example 17 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project xian by happyyangyuan.

the class TestDistributedPriorityQueue method testSortingWhileTaking.

@Test
public void testSortingWhileTaking() throws Exception {
    Timing timing = new Timing();
    DistributedPriorityQueue<Integer> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try {
        final BlockingQueue<Integer> blockingQueue = new SynchronousQueue<Integer>();
        QueueConsumer<Integer> consumer = new QueueConsumer<Integer>() {

            @Override
            public void consumeMessage(Integer message) throws Exception {
                blockingQueue.put(message);
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0);
        queue.start();
        for (int i = 0; i < 10; ++i) {
            queue.put(i, 10);
        }
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(0));
        timing.sleepABit();
        // lower priority
        queue.put(1000, 1);
        timing.sleepABit();
        // is in consumer already
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1));
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1000));
    } finally {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) SynchronousQueue(java.util.concurrent.SynchronousQueue) Timing(org.apache.curator.test.Timing) ConnectionState(org.apache.curator.framework.state.ConnectionState) Test(org.testng.annotations.Test)

Example 18 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project spring-integration by spring-projects.

the class MethodInvokingMessageHandlerTests method subscription.

@Test
public void subscription() throws Exception {
    TestApplicationContext context = TestUtils.createTestApplicationContext();
    SynchronousQueue<String> queue = new SynchronousQueue<String>();
    TestBean testBean = new TestBean(queue);
    QueueChannel channel = new QueueChannel();
    context.registerChannel("channel", channel);
    Message<String> message = new GenericMessage<String>("testing");
    channel.send(message);
    assertNull(queue.poll());
    MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(testBean, "foo");
    PollingConsumer endpoint = new PollingConsumer(channel, handler);
    endpoint.setTrigger(new PeriodicTrigger(10));
    context.registerEndpoint("testEndpoint", endpoint);
    context.refresh();
    String result = queue.poll(2000, TimeUnit.MILLISECONDS);
    assertNotNull(result);
    assertEquals("testing", result);
    context.stop();
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) MethodInvokingMessageHandler(org.springframework.integration.handler.MethodInvokingMessageHandler) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) QueueChannel(org.springframework.integration.channel.QueueChannel) SynchronousQueue(java.util.concurrent.SynchronousQueue) TestApplicationContext(org.springframework.integration.test.util.TestUtils.TestApplicationContext) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) Test(org.junit.Test)

Example 19 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project ma-core-public by infiniteautomation.

the class RealTimeTimer method init.

@Override
public void init() {
    ownsExecutor = true;
    init(new ThreadPoolExecutor(0, 1000, 30L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()));
}
Also used : SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 20 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project drill by axbaretto.

the class DrillClient method connect.

/**
 * Start's a connection from client to server
 * @param connect - Zookeeper connection string provided at connection URL
 * @param props - not null {@link Properties} filled with connection url parameters
 * @throws RpcException
 */
public synchronized void connect(String connect, Properties props) throws RpcException {
    if (connected) {
        return;
    }
    properties = DrillProperties.createFromProperties(props);
    final List<DrillbitEndpoint> endpoints = new ArrayList<>();
    if (isDirectConnection) {
        // Populate the endpoints list with all the drillbit information provided in the connection string
        endpoints.addAll(parseAndVerifyEndpoints(properties.getProperty(DrillProperties.DRILLBIT_CONNECTION), config.getString(ExecConstants.INITIAL_USER_PORT)));
    } else {
        if (ownsZkConnection) {
            try {
                this.clusterCoordinator = new ZKClusterCoordinator(this.config, connect);
                this.clusterCoordinator.start(10000);
            } catch (Exception e) {
                throw new RpcException("Failure setting up ZK for client.", e);
            }
        }
        // Gets the drillbit endpoints that are ONLINE and excludes the drillbits that are
        // in QUIESCENT state. This avoids the clients connecting to drillbits that are
        // shutting down thereby avoiding reducing the chances of query failures.
        endpoints.addAll(clusterCoordinator.getOnlineEndPoints());
        // Make sure we have at least one endpoint in the list
        checkState(!endpoints.isEmpty(), "No active Drillbit endpoint found from ZooKeeper. Check connection parameters?");
    }
    // shuffle the collection then get the first endpoint
    Collections.shuffle(endpoints);
    eventLoopGroup = createEventLoop(config.getInt(ExecConstants.CLIENT_RPC_THREADS), "Client-");
    executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("drill-client-executor-")) {

        @Override
        protected void afterExecute(final Runnable r, final Throwable t) {
            if (t != null) {
                logger.error("{}.run() leaked an exception.", r.getClass().getName(), t);
            }
            super.afterExecute(r, t);
        }
    };
    final String connectTriesConf = properties.getProperty(DrillProperties.TRIES, "5");
    int connectTriesVal;
    try {
        connectTriesVal = Math.min(endpoints.size(), Integer.parseInt(connectTriesConf));
    } catch (NumberFormatException e) {
        throw new InvalidConnectionInfoException("Invalid tries value: " + connectTriesConf + " specified in " + "connection string");
    }
    // If the value provided in the connection string is <=0 then override with 1 since we want to try connecting
    // at least once
    connectTriesVal = Math.max(1, connectTriesVal);
    int triedEndpointIndex = 0;
    DrillbitEndpoint endpoint;
    while (triedEndpointIndex < connectTriesVal) {
        endpoint = endpoints.get(triedEndpointIndex);
        // version
        if (!properties.containsKey(DrillProperties.SERVICE_HOST)) {
            properties.setProperty(DrillProperties.SERVICE_HOST, endpoint.getAddress());
            props.setProperty(DrillProperties.SERVICE_HOST, endpoint.getAddress());
        }
        // Note: the properties member is a DrillProperties instance which lower cases names of
        // properties. That does not work too well with properties that are mixed case.
        // For user client severla properties are mixed case so we do not use the properties member
        // but instead pass the props parameter.
        client = new UserClient(clientName, config, props, supportComplexTypes, allocator, eventLoopGroup, executor, endpoint);
        logger.debug("Connecting to server {}:{}", endpoint.getAddress(), endpoint.getUserPort());
        try {
            connect(endpoint);
            connected = true;
            logger.info("Successfully connected to server {}:{}", endpoint.getAddress(), endpoint.getUserPort());
            break;
        } catch (NonTransientRpcException ex) {
            logger.error("Connection to {}:{} failed with error {}. Not retrying anymore", endpoint.getAddress(), endpoint.getUserPort(), ex.getMessage());
            throw ex;
        } catch (RpcException ex) {
            ++triedEndpointIndex;
            logger.error("Attempt {}: Failed to connect to server {}:{}", triedEndpointIndex, endpoint.getAddress(), endpoint.getUserPort());
            // Throw exception when we have exhausted all the tries without having a successful connection
            if (triedEndpointIndex == connectTriesVal) {
                throw ex;
            }
            // Close the connection here to avoid calling close twice in case when all tries are exhausted.
            // Since DrillClient.close is also calling client.close
            client.close();
        }
    }
}
Also used : UserClient(org.apache.drill.exec.rpc.user.UserClient) NamedThreadFactory(org.apache.drill.exec.rpc.NamedThreadFactory) ArrayList(java.util.ArrayList) NonTransientRpcException(org.apache.drill.exec.rpc.NonTransientRpcException) ZKClusterCoordinator(org.apache.drill.exec.coord.zk.ZKClusterCoordinator) UserException(org.apache.drill.common.exceptions.UserException) RpcException(org.apache.drill.exec.rpc.RpcException) ChannelClosedException(org.apache.drill.exec.rpc.ChannelClosedException) OutOfMemoryException(org.apache.drill.exec.exception.OutOfMemoryException) NonTransientRpcException(org.apache.drill.exec.rpc.NonTransientRpcException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DrillbitEndpoint(org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint) DrillbitEndpoint(org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint) RpcException(org.apache.drill.exec.rpc.RpcException) NonTransientRpcException(org.apache.drill.exec.rpc.NonTransientRpcException) SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Aggregations

SynchronousQueue (java.util.concurrent.SynchronousQueue)117 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)61 ExecutorService (java.util.concurrent.ExecutorService)20 ThreadFactory (java.util.concurrent.ThreadFactory)14 ArrayList (java.util.ArrayList)12 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)12 IOException (java.io.IOException)9 RejectedExecutionHandler (java.util.concurrent.RejectedExecutionHandler)9 Test (org.junit.Test)9 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)7 BlockingQueue (java.util.concurrent.BlockingQueue)7 XMPPException (org.jivesoftware.smack.XMPPException)7 Future (java.util.concurrent.Future)6 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 XMPPConnection (org.jivesoftware.smack.XMPPConnection)5 List (java.util.List)4