Example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

List of usage examples for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

Introduction

In this page you can find the example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue.

Prototype

public LinkedBlockingQueue() 

Source Link

Document

Creates a LinkedBlockingQueue with a capacity of Integer#MAX_VALUE .

Usage

From source file:com.jbrisbin.vpc.jobsched.SubmitClosure.java

@Override
public Object call(Object[] args) {
    log.debug("args: " + args);
    String exch = args[0].toString();
    String route = args[1].toString();
    final Object body = args[2];
    Map headers = null;/* ww w  . j a  v a2s  .  co  m*/

    final BlockingQueue<Object> resultsQueue = new LinkedBlockingQueue<Object>();
    Queue replyQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer();
    listener.setQueues(replyQueue);
    if (args.length > 3) {
        for (int i = 3; i <= args.length; i++) {
            if (args[i] instanceof MessageListener) {
                MessageListener callback = (MessageListener) args[3];
                listener.setMessageListener(callback);
            } else if (args[i] instanceof Map) {
                headers = (Map) args[i];
            }
        }
    } else {
        listener.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                byte[] body = message.getBody();
                try {
                    resultsQueue.add(mapper.readValue(body, 0, body.length, Map.class));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    final Map msgHdrs = headers;
    rabbitTemplate.send(exch, route, new MessageCreator() {
        public Message createMessage() {
            MessageProperties props = new RabbitMessageProperties();
            props.setContentType("application/json");
            if (null != msgHdrs) {
                props.getHeaders().putAll(msgHdrs);
            }
            String uuid = UUID.randomUUID().toString();
            props.setCorrelationId(uuid.getBytes());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                mapper.writeValue(out, body);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            Message msg = new Message(out.toByteArray(), props);
            return msg;
        }
    });

    Object results = null;
    try {
        results = resultsQueue.poll(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    }
    listener.stop();

    return results;
}

From source file:io.cloudslang.lang.systemtests.TriggerFlows.java

public ScoreEvent runSync(CompilationArtifact compilationArtifact,
        Map<String, ? extends Serializable> userInputs, Set<SystemProperty> systemProperties) {
    final BlockingQueue<ScoreEvent> finishEvent = new LinkedBlockingQueue<>();
    ScoreEventListener finishListener = new ScoreEventListener() {
        @Override//from   ww  w.  ja v a 2  s.  c  om
        public synchronized void onEvent(ScoreEvent event) throws InterruptedException {
            finishEvent.add(event);
        }
    };
    slang.subscribeOnEvents(finishListener, FINISHED_EVENTS);

    slang.run(compilationArtifact, userInputs, systemProperties);

    try {
        ScoreEvent event = finishEvent.take();
        if (event.getEventType().equals(ScoreLangConstants.SLANG_EXECUTION_EXCEPTION)) {
            LanguageEventData languageEvent = (LanguageEventData) event.getData();
            throw new RuntimeException(languageEvent.getException());
        }
        slang.unSubscribeOnEvents(finishListener);
        return event;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:dk.netarkivet.wayback.indexer.IndexerQueue.java

/**
 * Private constructor for this method. Initialises an empty queue.
 */
private IndexerQueue() {
    queue = new LinkedBlockingQueue<ArchiveFile>();
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Plugin.java

private Plugin() {
    final int CORES = Runtime.getRuntime().availableProcessors();
    final int THREAD_POOL_SIZE_NETWORK = CORES + 1;
    final int THREAD_POOL_SIZE_NETWORK_MAX = CORES * 2 + 1;
    final long KEEP_ALIVE_VALUE = 1;
    final TimeUnit KEEP_ALIVE_VALUE_TIME_UNIT = TimeUnit.SECONDS;
    final int CACHE_BITMAP_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8192f);

    cacheBitmap = new LruCache<String, Bitmap>(CACHE_BITMAP_SIZE) {
        @Override//  w  ww.j  a va2 s .c  o m
        protected int sizeOf(String key, Bitmap bitmap) {
            return (int) ((bitmap.getRowBytes() * bitmap.getHeight()) / 1024f);
        }
    };

    queueNetwork = new LinkedBlockingQueue<>();
    queueLocal = new LinkedBlockingQueue<>();

    threadPoolNetwork = new ThreadPoolExecutor(THREAD_POOL_SIZE_NETWORK, THREAD_POOL_SIZE_NETWORK_MAX,
            KEEP_ALIVE_VALUE, KEEP_ALIVE_VALUE_TIME_UNIT, queueNetwork);
    threadPoolLocal = new ThreadPoolExecutor(CORES, CORES, KEEP_ALIVE_VALUE, KEEP_ALIVE_VALUE_TIME_UNIT,
            queueLocal);
}

From source file:baggage.BaseTestCase.java

protected void setUp() throws Exception {
    eventQueue = new LinkedBlockingQueue<String>();
    randomInt = (int) (Math.random() * 100000d);
    randomByte = (byte) (Math.random() * 127d);
    randomLong = randomLong();//from w ww .  ja v a2 s .c om
    randomString = randomString(32);
}

From source file:pl.bristleback.server.bristle.message.akka.SingleThreadMessageDispatcher.java

public SingleThreadMessageDispatcher() {
    messages = new LinkedBlockingQueue<WebsocketMessage>();
}

From source file:CreateTest.java

static void doTestPool(int nThreads) {
    done = false;/*from w  ww.ja va2 s  .  c  o  m*/
    nCalls = new AtomicInteger(0);
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(nThreads, nThreads, 50000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    Runnable r = new CreateTest();
    for (int i = 0; i < target; i++) {
        tpe.execute(r);
    }
    tpe.shutdown();
    try {
        tpe.awaitTermination(10000000L, TimeUnit.SECONDS);
    } catch (Exception e) {
    }
}

From source file:org.sourcepit.docker.watcher.DockerWatcher.java

public synchronized void start() {
    isTrue(client == null);//from w w w. ja va  2  s.co m
    isTrue(eventObserverThread == null);
    isTrue(scheduler == null);

    final State state = new State() {
        @Override
        protected void handle(List<JsonObject> events) {
            DockerWatcher.this.handle(events);
        }
    };

    final BlockingQueue<JsonElement> queue = new LinkedBlockingQueue<>();

    client = clientFactory.createHttpClient();

    final FetchConatinersCommand fetchContainersCommand = new FetchConatinersCommand(client, uri) {
        @Override
        protected void handle(JsonArray status) {
            LOG.debug("Fetched: {}", status.toString());
            queue.add(status);
        }
    };

    final DockerEventObserver eventObserver = new DockerEventObserver(client, uri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(event);
        }
    };

    eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };

    scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Docker State Fetcher");
        }
    });

    final SyncStateCommand syncStateCommand = new SyncStateCommand(queue) {

        @Override
        protected void requestNewStatus() {
            LOG.debug("Requesting new status.");
            scheduler.execute(fetchContainersCommand);
        }

        @Override
        protected void applyLastKnownState(JsonArray status) {
            LOG.debug("Applying new status: {}", status.toString());
            state.applyLastKnownState(status);
        }

    };

    scheduler.scheduleWithFixedDelay(fetchContainersCommand, 0, 30, TimeUnit.SECONDS);
    scheduler.scheduleWithFixedDelay(syncStateCommand, 0, 1, TimeUnit.SECONDS);
    eventObserverThread.start();
}

From source file:com.ibuildapp.ZopimChatPlugin.core.Core.java

Core() {
    final int CORES = Runtime.getRuntime().availableProcessors();
    final int THREAD_POOL_SIZE_NETWORK = CORES + 1;
    final int THREAD_POOL_SIZE_NETWORK_MAX = CORES * 2 + 1;
    final long KEEP_ALIVE_VALUE = 1;
    final TimeUnit KEEP_ALIVE_VALUE_TIME_UNIT = TimeUnit.SECONDS;
    final int CACHE_BITMAP_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8192f);

    cacheBitmap = new LruCache<String, Bitmap>(CACHE_BITMAP_SIZE) {
        @Override/* www . j  a v a2  s .c o m*/
        protected int sizeOf(String key, Bitmap bitmap) {
            return (int) ((bitmap.getRowBytes() * bitmap.getHeight()) / 1024f);
        }
    };

    queueNetwork = new LinkedBlockingQueue<>();
    queueLocal = new LinkedBlockingQueue<>();

    threadPoolNetwork = new ThreadPoolExecutor(THREAD_POOL_SIZE_NETWORK, THREAD_POOL_SIZE_NETWORK_MAX,
            KEEP_ALIVE_VALUE, KEEP_ALIVE_VALUE_TIME_UNIT, queueNetwork);
    threadPoolLocal = new ThreadPoolExecutor(CORES, CORES, KEEP_ALIVE_VALUE, KEEP_ALIVE_VALUE_TIME_UNIT,
            queueLocal);
}

From source file:com.android.bitmap.AltPooledCache.java

/**
 * @param targetSize not exactly a max size in practice
 * @param nonPooledFraction the fractional portion in the range [0.0,1.0] of targetSize to
 * dedicate to non-poolable entries/*from  w  w  w.j av a  2s  .c  o  m*/
 */
public AltPooledCache(int targetSize, float nonPooledFraction) {
    mCache = new LinkedHashMap<K, V>(0, 0.75f, true);
    mPool = new LinkedBlockingQueue<V>();
    final int nonPooledSize = Math.round(targetSize * nonPooledFraction);
    if (nonPooledSize > 0) {
        mNonPooledCache = new NonPooledCache(nonPooledSize);
    } else {
        mNonPooledCache = null;
    }
    mTargetSize = targetSize - nonPooledSize;
}