Search in sources :

Example 66 with LinkedBlockingQueue

use of java.util.concurrent.LinkedBlockingQueue in project android_frameworks_base by ParanoidAndroid.

the class KeyChain method bind.

/**
     * @hide for reuse by CertInstaller and Settings.
     *
     * Caller should call unbindService on the result when finished.
     */
public static KeyChainConnection bind(Context context) throws InterruptedException {
    if (context == null) {
        throw new NullPointerException("context == null");
    }
    ensureNotOnMainThread(context);
    final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
    ServiceConnection keyChainServiceConnection = new ServiceConnection() {

        volatile boolean mConnectedAtLeastOnce = false;

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (!mConnectedAtLeastOnce) {
                mConnectedAtLeastOnce = true;
                try {
                    q.put(IKeyChainService.Stub.asInterface(service));
                } catch (InterruptedException e) {
                // will never happen, since the queue starts with one available slot
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    boolean isBound = context.bindService(new Intent(IKeyChainService.class.getName()), keyChainServiceConnection, Context.BIND_AUTO_CREATE);
    if (!isBound) {
        throw new AssertionError("could not bind to KeyChainService");
    }
    return new KeyChainConnection(context, keyChainServiceConnection, q.take());
}
Also used : ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) ComponentName(android.content.ComponentName) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue)

Example 67 with LinkedBlockingQueue

use of java.util.concurrent.LinkedBlockingQueue in project storm by nathanmarz.

the class ShellBolt method prepare.

public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) {
    Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING);
    if (maxPending != null) {
        this._pendingWrites = new LinkedBlockingQueue(((Number) maxPending).intValue());
    }
    _rand = new Random();
    _process = new ShellProcess(_command);
    _collector = collector;
    try {
        //subprocesses must send their pid first thing
        Number subpid = _process.launch(stormConf, context);
        LOG.info("Launched subprocess with pid " + subpid);
    } catch (IOException e) {
        throw new RuntimeException("Error when launching multilang subprocess\n" + _process.getErrorsString(), e);
    }
    // reader
    _readerThread = new Thread(new Runnable() {

        public void run() {
            while (_running) {
                try {
                    JSONObject action = _process.readMessage();
                    if (action == null) {
                    // ignore sync
                    }
                    String command = (String) action.get("command");
                    if (command.equals("ack")) {
                        handleAck(action);
                    } else if (command.equals("fail")) {
                        handleFail(action);
                    } else if (command.equals("error")) {
                        handleError(action);
                    } else if (command.equals("log")) {
                        String msg = (String) action.get("msg");
                        LOG.info("Shell msg: " + msg);
                    } else if (command.equals("emit")) {
                        handleEmit(action);
                    }
                } catch (InterruptedException e) {
                } catch (Throwable t) {
                    die(t);
                }
            }
        }
    });
    _readerThread.start();
    _writerThread = new Thread(new Runnable() {

        public void run() {
            while (_running) {
                try {
                    Object write = _pendingWrites.poll(1, SECONDS);
                    if (write != null) {
                        _process.writeMessage(write);
                    }
                    // drain the error stream to avoid dead lock because of full error stream buffer
                    _process.drainErrorStream();
                } catch (InterruptedException e) {
                } catch (Throwable t) {
                    die(t);
                }
            }
        }
    });
    _writerThread.start();
}
Also used : ShellProcess(backtype.storm.utils.ShellProcess) IOException(java.io.IOException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Random(java.util.Random) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject)

Example 68 with LinkedBlockingQueue

use of java.util.concurrent.LinkedBlockingQueue in project netty by netty.

the class DefaultChannelPipelineTest method testHandlerAddedAndRemovedCalledInCorrectOrder.

@Test(timeout = 3000)
public void testHandlerAddedAndRemovedCalledInCorrectOrder() throws Throwable {
    final EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    final EventExecutorGroup group2 = new DefaultEventExecutorGroup(1);
    try {
        BlockingQueue<CheckOrderHandler> addedQueue = new LinkedBlockingQueue<CheckOrderHandler>();
        BlockingQueue<CheckOrderHandler> removedQueue = new LinkedBlockingQueue<CheckOrderHandler>();
        CheckOrderHandler handler1 = new CheckOrderHandler(addedQueue, removedQueue);
        CheckOrderHandler handler2 = new CheckOrderHandler(addedQueue, removedQueue);
        CheckOrderHandler handler3 = new CheckOrderHandler(addedQueue, removedQueue);
        CheckOrderHandler handler4 = new CheckOrderHandler(addedQueue, removedQueue);
        ChannelPipeline pipeline = new LocalChannel().pipeline();
        pipeline.addLast(handler1);
        group.register(pipeline.channel()).syncUninterruptibly();
        pipeline.addLast(group1, handler2);
        pipeline.addLast(group2, handler3);
        pipeline.addLast(handler4);
        assertTrue(removedQueue.isEmpty());
        pipeline.channel().close().syncUninterruptibly();
        assertHandler(addedQueue.take(), handler1);
        // Depending on timing this can be handler2 or handler3 as these use different EventExecutorGroups.
        assertHandler(addedQueue.take(), handler2, handler3, handler4);
        assertHandler(addedQueue.take(), handler2, handler3, handler4);
        assertHandler(addedQueue.take(), handler2, handler3, handler4);
        assertTrue(addedQueue.isEmpty());
        assertHandler(removedQueue.take(), handler4);
        assertHandler(removedQueue.take(), handler3);
        assertHandler(removedQueue.take(), handler2);
        assertHandler(removedQueue.take(), handler1);
        assertTrue(removedQueue.isEmpty());
    } finally {
        group1.shutdownGracefully();
        group2.shutdownGracefully();
    }
}
Also used : DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) LocalChannel(io.netty.channel.local.LocalChannel) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Test(org.junit.Test)

Example 69 with LinkedBlockingQueue

use of java.util.concurrent.LinkedBlockingQueue in project netty by netty.

the class BootstrapTest method testLateRegisterSuccessBindFailed.

@Test
public void testLateRegisterSuccessBindFailed() throws Exception {
    TestEventLoopGroup group = new TestEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group);
        bootstrap.channelFactory(new ChannelFactory<ServerChannel>() {

            @Override
            public ServerChannel newChannel() {
                return new LocalServerChannel() {

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return newFailedFuture(new SocketException());
                    }

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return promise.setFailure(new SocketException());
                    }
                };
            }
        });
        bootstrap.childHandler(new DummyHandler());
        bootstrap.localAddress(new LocalAddress("1"));
        ChannelFuture future = bootstrap.bind();
        assertFalse(future.isDone());
        group.promise.setSuccess();
        final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
                queue.add(future.isSuccess());
            }
        });
        assertTrue(queue.take());
        assertFalse(queue.take());
    } finally {
        group.shutdownGracefully();
        group.terminationFuture().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketException(java.net.SocketException) LocalAddress(io.netty.channel.local.LocalAddress) ChannelPromise(io.netty.channel.ChannelPromise) LocalServerChannel(io.netty.channel.local.LocalServerChannel) ServerChannel(io.netty.channel.ServerChannel) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketException(java.net.SocketException) ConnectException(java.net.ConnectException) UnknownHostException(java.net.UnknownHostException) LocalServerChannel(io.netty.channel.local.LocalServerChannel) SocketAddress(java.net.SocketAddress) Test(org.junit.Test)

Example 70 with LinkedBlockingQueue

use of java.util.concurrent.LinkedBlockingQueue in project neo4j by neo4j.

the class BatchingMultipleIndexPopulator method createThreadPool.

private ExecutorService createThreadPool() {
    int threads = getNumberOfPopulationWorkers();
    BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(TASK_QUEUE_SIZE);
    ThreadFactory threadFactory = daemon(FLUSH_THREAD_NAME_PREFIX);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    return new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, workQueue, threadFactory, rejectedExecutionHandler);
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue)

Aggregations

LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)259 Test (org.junit.Test)91 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)64 IOException (java.io.IOException)26 ArrayList (java.util.ArrayList)23 Emitter (io.socket.emitter.Emitter)19 JSONObject (org.json.JSONObject)19 CountDownLatch (java.util.concurrent.CountDownLatch)18 ThreadFactory (java.util.concurrent.ThreadFactory)16 ExecutorService (java.util.concurrent.ExecutorService)14 BlockingQueue (java.util.concurrent.BlockingQueue)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 List (java.util.List)12 URI (java.net.URI)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 Intent (android.content.Intent)9 HashMap (java.util.HashMap)9 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)8 Map (java.util.Map)8 UUID (java.util.UUID)8