Search in sources :

Example 61 with ArrayBlockingQueue

use of java.util.concurrent.ArrayBlockingQueue in project sling by apache.

the class ManagerSubscriberTest method setUp.

@Before
public void setUp() throws Exception {
    topicQueues = new HashMap<org.apache.sling.mom.Types.TopicName, Queue<QueueEntry>>();
    messageQueues = new HashMap<org.apache.sling.mom.Types.QueueName, Queue<QueueEntry>>();
    //noinspection unchecked
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            org.apache.sling.mom.Types.TopicName topic = (org.apache.sling.mom.Types.TopicName) invocationOnMock.getArguments()[0];
            org.apache.sling.mom.Types.CommandName command = (org.apache.sling.mom.Types.CommandName) invocationOnMock.getArguments()[1];
            @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>) invocationOnMock.getArguments()[2];
            Queue<QueueEntry> queue = topicQueues.get(topic);
            if (queue == null) {
                queue = new ArrayBlockingQueue<QueueEntry>(100);
                topicQueues.put(topic, queue);
            }
            queue.add(new QueueEntry(command, properties));
            return null;
        }
    }).when(topicManager).publish(Mockito.any(org.apache.sling.mom.Types.TopicName.class), Mockito.any(org.apache.sling.mom.Types.CommandName.class), Mockito.any(Map.class));
    //noinspection unchecked
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            org.apache.sling.mom.Types.QueueName topic = (org.apache.sling.mom.Types.QueueName) invocationOnMock.getArguments()[0];
            @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>) invocationOnMock.getArguments()[1];
            Queue<QueueEntry> queue = messageQueues.get(topic);
            if (queue == null) {
                queue = new ArrayBlockingQueue<QueueEntry>(100);
                messageQueues.put(topic, queue);
            }
            queue.add(new QueueEntry(properties));
            return null;
        }
    }).when(queueManager).add(Mockito.any(org.apache.sling.mom.Types.QueueName.class), Mockito.any(Map.class));
    messageSender = new OutboundJobUpdateListener(topicManager, queueManager);
    jobStorage = new InMemoryJobStorage();
    jobManager = new JobManagerImpl(jobStorage, messageSender);
    managerSubscriber = new ManagerSubscriber();
    Field f = managerSubscriber.getClass().getDeclaredField("jobManager");
    f.setAccessible(true);
    f.set(managerSubscriber, jobManager);
}
Also used : Types(org.apache.sling.jobs.Types) Field(java.lang.reflect.Field) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Queue(java.util.Queue) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InMemoryJobStorage(org.apache.sling.jobs.impl.storage.InMemoryJobStorage) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 62 with ArrayBlockingQueue

use of java.util.concurrent.ArrayBlockingQueue in project android_frameworks_base by crdroidandroid.

the class LoaderTestCase method getLoaderResultSynchronously.

/**
     * Runs a Loader synchronously and returns the result of the load. The loader will
     * be started, stopped, and destroyed by this method so it cannot be reused.
     *
     * @param loader The loader to run synchronously
     * @return The result from the loader
     */
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
    // The test thread blocks on this queue until the loader puts it's result in
    final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);
    // This callback runs on the "main" thread and unblocks the test thread
    // when it puts the result into the blocking queue
    final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {

        @Override
        public void onLoadComplete(Loader<T> completedLoader, T data) {
            // Shut the loader down
            completedLoader.unregisterListener(this);
            completedLoader.stopLoading();
            completedLoader.reset();
            // Store the result, unblocking the test thread
            queue.add(data);
        }
    };
    // This handler runs on the "main" thread of the process since AsyncTask
    // is documented as needing to run on the main thread and many Loaders use
    // AsyncTask
    final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            loader.registerListener(0, listener);
            loader.startLoading();
        }
    };
    // Ask the main thread to start the loading process
    mainThreadHandler.sendEmptyMessage(0);
    // Block on the queue waiting for the result of the load to be inserted
    T result;
    while (true) {
        try {
            result = queue.take();
            break;
        } catch (InterruptedException e) {
            throw new RuntimeException("waiting thread interrupted", e);
        }
    }
    return result;
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Message(android.os.Message) OnLoadCompleteListener(android.content.Loader.OnLoadCompleteListener) Loader(android.content.Loader) Handler(android.os.Handler)

Example 63 with ArrayBlockingQueue

use of java.util.concurrent.ArrayBlockingQueue in project rabbitmq-java-client by rabbitmq.

the class ConnectionFactoryTest method tryNextAddressIfTimeoutExceptionNoAutoRecovery.

// see https://github.com/rabbitmq/rabbitmq-java-client/issues/262
@Test
public void tryNextAddressIfTimeoutExceptionNoAutoRecovery() throws IOException, TimeoutException {
    final AMQConnection connectionThatThrowsTimeout = mock(AMQConnection.class);
    final AMQConnection connectionThatSucceeds = mock(AMQConnection.class);
    final Queue<AMQConnection> connections = new ArrayBlockingQueue<AMQConnection>(10);
    connections.add(connectionThatThrowsTimeout);
    connections.add(connectionThatSucceeds);
    ConnectionFactory connectionFactory = new ConnectionFactory() {

        @Override
        protected AMQConnection createConnection(ConnectionParams params, FrameHandler frameHandler, MetricsCollector metricsCollector) {
            return connections.poll();
        }

        @Override
        protected synchronized FrameHandlerFactory createFrameHandlerFactory() throws IOException {
            return mock(FrameHandlerFactory.class);
        }
    };
    connectionFactory.setAutomaticRecoveryEnabled(false);
    doThrow(TimeoutException.class).when(connectionThatThrowsTimeout).start();
    doNothing().when(connectionThatSucceeds).start();
    Connection returnedConnection = connectionFactory.newConnection(new Address[] { new Address("host1"), new Address("host2") });
    assertSame(connectionThatSucceeds, returnedConnection);
}
Also used : MetricsCollector(com.rabbitmq.client.MetricsCollector) FrameHandler(com.rabbitmq.client.impl.FrameHandler) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Address(com.rabbitmq.client.Address) AMQConnection(com.rabbitmq.client.impl.AMQConnection) AMQConnection(com.rabbitmq.client.impl.AMQConnection) Connection(com.rabbitmq.client.Connection) ConnectionParams(com.rabbitmq.client.impl.ConnectionParams) Test(org.junit.Test)

Example 64 with ArrayBlockingQueue

use of java.util.concurrent.ArrayBlockingQueue in project linuxtools by eclipse.

the class ImageTagSelectionPage method searchTags.

private void searchTags() {
    try {
        final BlockingQueue<List<DockerImageTagSearchResult>> searchResultQueue = new ArrayBlockingQueue<>(1);
        ImageTagSelectionPage.this.getContainer().run(true, true, monitor -> {
            monitor.beginTask(WizardMessages.getString(// $NON-NLS-1$
            "ImageTagSelectionPage.searchTask"), 2);
            final String selectedImageName = ImageTagSelectionPage.this.model.getSelectedImage().getName();
            try {
                final List<IRepositoryTag> repositoryTags = registry.getTags(selectedImageName);
                // we have to convert to list of RepositoryTag which
                // can be sorted
                final List<RepositoryTag> tags = repositoryTags.stream().map(c -> (RepositoryTag) c).collect(Collectors.toList());
                Collections.sort(tags);
                monitor.worked(1);
                final IDockerConnection connection = model.getSelectedConnection();
                final List<DockerImageTagSearchResult> searchResults = repositoryTags.stream().map(t -> new DockerImageTagSearchResult(selectedImageName, t, connection.hasImage(selectedImageName, t.getName()))).collect(Collectors.toList());
                monitor.worked(1);
                searchResultQueue.offer(searchResults);
            } catch (DockerException e) {
            } finally {
                monitor.done();
            }
        });
        List<DockerImageTagSearchResult> res = searchResultQueue.poll(10, TimeUnit.SECONDS);
        final List<DockerImageTagSearchResult> searchResult = (res == null) ? new ArrayList<>() : res;
        Display.getCurrent().asyncExec(() -> {
            ImageTagSelectionPage.this.model.setImageTagSearchResult(searchResult);
            // refresh the wizard buttons
            getWizard().getContainer().updateButtons();
        });
        // display a warning in the title area if the search result is empty
        if (searchResult.isEmpty()) {
            this.setMessage(WizardMessages.getString(// $NON-NLS-1$
            "ImageTagSelectionPage.noTagWarning"), WARNING);
        } else if (searchResult.size() == 1) {
            this.setMessage(WizardMessages.getString(// $NON-NLS-1$
            "ImageTagSelectionPage.oneTagMatched"), INFORMATION);
        } else {
            this.setMessage(WizardMessages.getFormattedString(// $NON-NLS-1$
            "ImageTagSelectionPage.tagsMatched", Integer.toString(searchResult.size())), INFORMATION);
        }
    } catch (InvocationTargetException | InterruptedException e) {
        Activator.log(e);
    }
}
Also used : IRepositoryTag(org.eclipse.linuxtools.docker.core.IRepositoryTag) TableViewer(org.eclipse.jface.viewers.TableViewer) Activator(org.eclipse.linuxtools.docker.ui.Activator) TableColumn(org.eclipse.swt.widgets.TableColumn) DataBindingContext(org.eclipse.core.databinding.DataBindingContext) ObservableListContentProvider(org.eclipse.jface.databinding.viewers.ObservableListContentProvider) Table(org.eclipse.swt.widgets.Table) ArrayList(java.util.ArrayList) IObservableList(org.eclipse.core.databinding.observable.list.IObservableList) RepositoryTag(org.eclipse.linuxtools.internal.docker.core.RepositoryTag) Composite(org.eclipse.swt.widgets.Composite) DockerException(org.eclipse.linuxtools.docker.core.DockerException) IconColumnLabelProvider(org.eclipse.linuxtools.internal.docker.ui.wizards.ImageSearchPage.IconColumnLabelProvider) WizardPage(org.eclipse.jface.wizard.WizardPage) GridDataFactory(org.eclipse.jface.layout.GridDataFactory) ViewerProperties(org.eclipse.jface.databinding.viewers.ViewerProperties) BlockingQueue(java.util.concurrent.BlockingQueue) IRegistry(org.eclipse.linuxtools.docker.core.IRegistry) Display(org.eclipse.swt.widgets.Display) ColumnLabelProvider(org.eclipse.jface.viewers.ColumnLabelProvider) Collectors(java.util.stream.Collectors) TableViewerColumn(org.eclipse.jface.viewers.TableViewerColumn) GridLayoutFactory(org.eclipse.jface.layout.GridLayoutFactory) InvocationTargetException(java.lang.reflect.InvocationTargetException) CellLabelProvider(org.eclipse.jface.viewers.CellLabelProvider) TimeUnit(java.util.concurrent.TimeUnit) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) List(java.util.List) SWTImagesFactory(org.eclipse.linuxtools.internal.docker.ui.SWTImagesFactory) BeanProperties(org.eclipse.core.databinding.beans.BeanProperties) SWT(org.eclipse.swt.SWT) RepositoryTagV2(org.eclipse.linuxtools.internal.docker.core.RepositoryTagV2) Collections(java.util.Collections) IRepositoryTag(org.eclipse.linuxtools.docker.core.IRepositoryTag) DockerException(org.eclipse.linuxtools.docker.core.DockerException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) IDockerConnection(org.eclipse.linuxtools.docker.core.IDockerConnection) RepositoryTag(org.eclipse.linuxtools.internal.docker.core.RepositoryTag) IRepositoryTag(org.eclipse.linuxtools.docker.core.IRepositoryTag) ArrayList(java.util.ArrayList) IObservableList(org.eclipse.core.databinding.observable.list.IObservableList) List(java.util.List)

Example 65 with ArrayBlockingQueue

use of java.util.concurrent.ArrayBlockingQueue in project baseio by generallycloud.

the class ExecutorPoolEventLoop method startup.

@Override
public void startup(String threadName) throws Exception {
    threadFactory = new NamedThreadFactory(threadName);
    poolExecutor = new ThreadPoolExecutor(eventLoopSize, maxEventLoopSize, keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(maxEventQueueSize), threadFactory);
    running = true;
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Aggregations

ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)440 Test (org.junit.Test)158 ArrayList (java.util.ArrayList)75 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)74 IOException (java.io.IOException)66 CountDownLatch (java.util.concurrent.CountDownLatch)58 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)41 BlockingQueue (java.util.concurrent.BlockingQueue)34 ExecutorService (java.util.concurrent.ExecutorService)34 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)31 List (java.util.List)29 LocalAddress (io.netty.channel.local.LocalAddress)27 HashMap (java.util.HashMap)25 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)25 Subscription (rx.Subscription)25 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)24 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)23 File (java.io.File)22 CompletableFuture (java.util.concurrent.CompletableFuture)22 LinkedList (java.util.LinkedList)21