Example usage for java.util.concurrent BlockingQueue add

List of usage examples for java.util.concurrent BlockingQueue add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Usage

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

public static void main(String[] args) throws IOException {

    final HttpClientFactory clientFactory = new HttpClientFactory() {
        @Override//from   w ww.j a v  a  2s .  c  om
        public CloseableHttpClient createHttpClient() {
            return HttpClients.createDefault();
        }
    };

    final String dockerDaemonUri = "http://192.168.56.101:2375";
    final String consulAgentUri = "http://192.168.56.101:8500";

    final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>();

    final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(),
            consulAgentUri);

    final Thread containerStateDispatcher = new Thread("Consul Forwarder") {
        @Override
        public void run() {
            while (true) {
                try {
                    consulForwarder.forward(queue.take());
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    LOG.error("Error while forwarding Docker container state to Consul.", e);
                }
            }
        }
    };
    containerStateDispatcher.start();

    final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) {
        @Override
        protected void handle(List<JsonObject> containerState) {
            queue.add(containerState);
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            watcher.stop();
            while (containerStateDispatcher.isAlive()) {
                containerStateDispatcher.interrupt();
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    watcher.start();
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

public static void main(String[] args) {
    /*System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());
            //from w w w  .j  a v  a  2  s  . c  om
    SlaveState slaveState = new SlaveState();
    slaveState.setId(1L);
    slaveState.setIsMasterCandidate(false);
    Command command = CommandFactory.createHeartbeatCommand(slaveState.toByteBuffer());
    Packet packet = Packet.newDataPacket(command);
    ByteBuffer buffer = packet.marshall();
    Packet p = Packet.unmarshall(buffer);
    Command cmd = Command.unmarshall(p.getPayLoad());
    SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
    System.out.println(cmd.toString());
            
            
    // Test 2
    MasterState masterState = new MasterState();
    masterState.setId(1L);
    masterState.setIp("127.0.0.1");
    masterState.setPort(8206);
    List<SessionState> sessionStateList = new LinkedList<SessionState>();
    masterState.setSessionStateList(sessionStateList);
    SessionState sessionState = null;
    for(int i = 0; i < 10; i++) {
       sessionState = new SessionState();
       sessionState.setIp("127.0.0.1");
       sessionState.setPriority(1L);
       sessionState.setIsMasterCandidate(false);
       sessionStateList.add(sessionState);
    }
    Command command2 = CommandFactory.createHeartbeatCommand(masterState.toByteBuffer());
    Packet packet2 = Packet.newDataPacket(command2);
    ByteBuffer buffer2 = packet2.marshall();
    Packet p2 = Packet.unmarshall(buffer2);
    Command cmd2 = Command.unmarshall(p2.getPayLoad());
    MasterState ms = MasterState.fromByteBuffer(cmd2.getPayLoad());
    System.out.println(cmd.toString());
    */

    System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());

    BlockingQueue<ByteBuffer> queue = new LinkedBlockingQueue<ByteBuffer>();
    Random rand = new Random();
    int count = 0;
    int size = 0;
    for (int i = 0; i < 100000; i++) {
        SlaveState state = new SlaveState();
        state.setId(Long.valueOf(i));
        state.setIsMasterCandidate(true);
        Packet packet = Packet.newDataPacket(
                CommandFactory.createCommand(Command.AVAILABLE_COMMAND_START, state.toByteBuffer()));
        ByteBuffer buffer = packet.marshall();
        rand.setSeed(System.currentTimeMillis());
        count = rand.nextInt(100) + 1;
        size = buffer.remaining() / count;
        for (int j = 0; j < count; j++) {
            ByteBuffer buf = null;
            if (j == count - 1) {
                buf = ByteBuffer.allocate(buffer.remaining() - j * size);
                buf.put(buffer.array(), j * size, buffer.remaining() - j * size);
            } else {
                buf = ByteBuffer.allocate(size);
                buf.put(buffer.array(), j * size, size);
            }
            buf.flip();
            queue.add(buf);
        }
    }

    for (int i = 0; i < 100000; i++) {
        //Packet packet = Packet.parse(queue);
        //Command commad = Command.unmarshall(packet.getPayLoad());
        //SlaveState state = SlaveState.fromByteBuffer(commad.getPayLoad());
        //System.out.println(state.toString());
    }
}

From source file:cc.solr.lucene.store.BufferStore.java

private static BlockingQueue<byte[]> setupBuffers(int bufferSize, int count) {
    BlockingQueue<byte[]> queue = new ArrayBlockingQueue<byte[]>(count);
    for (int i = 0; i < count; i++) {
        queue.add(new byte[bufferSize]);
    }/*www . java 2 s  .  co  m*/
    return queue;
}

From source file:any.servable.EchoServable.java

public void process(String cmd, String content, BlockingQueue<Message> outQueue) {
    logger.info("ECHO Servable called with:" + content);
    outQueue.add(new Message("vset", "_echo", "text/plain", "NO", content.getBytes()));
}

From source file:org.bpmscript.integration.internal.memory.MemorySyncChannel.java

public void onMessage(IInternalMessage internalMessage) {
    String id = internalMessage.getCorrelationId();
    if (id == null) {
        log.error("correlationId for " + internalMessage + " is null");
    } else {//w  w  w .j  av a 2 s  . c o m
        BlockingQueue<Object> blockingQueue = replies.get(id);
        if (blockingQueue != null) {
            blockingQueue.add(internalMessage);
        }
    }
}

From source file:org.bpmscript.integration.spring.SpringSyncChannel.java

/**
 * Get the correlation id from the message, look up the right blocking queue to add 
 * it to./* w ww .  ja va 2 s. co  m*/
 */
public Message<?> handle(Message<?> message) {
    String id = (String) message.getHeader().getCorrelationId();
    if (id == null) {
        log.error("correlationId for " + message + " is null");
    } else {
        BlockingQueue<Object> blockingQueue = replies.get(id);
        if (blockingQueue != null) {
            blockingQueue.add(message);
        } else {
            log.warn("message with unknown correlation id " + message);
        }
    }
    return null;
}

From source file:fi.jumi.core.suite.SuiteFactoryTest.java

@Test
public void sets_the_context_class_loader_for_test_threads() throws InterruptedException {
    createSuiteFactory();/*from www.  j a va2s.  com*/

    factory.start(new NullSuiteListener());
    BlockingQueue<ClassLoader> spy = new LinkedBlockingQueue<>();

    factory.testThreadPool.execute(() -> {
        spy.add(Thread.currentThread().getContextClassLoader());
    });
    ClassLoader contextClassLoader = spy.take();

    assertThat(contextClassLoader, is(factory.testClassLoader));
}

From source file:org.apache.camel.impl.DefaultServicePool.java

public synchronized void release(Key key, Service service) {
    if (log.isTraceEnabled()) {
        log.trace("Release: " + key + " service: " + service);
    }/*from  w  w w  .j ava2  s.com*/
    BlockingQueue<Service> services = pool.get(key);
    if (services != null) {
        services.add(service);
    }
}

From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java

public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception {

    JanusGraphManagement mgmt = graph.openManagement();
    if (mgmt.getGraphIndex(CHARACTER) == null) {
        final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
        mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
    }//ww w  . j a va 2  s . c o  m
    if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
        final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
        mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
        mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
        mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
    }
    mgmt.commit();

    ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/marvel.csv");
    int line = 0;
    Map<String, Set<String>> comicToCharacter = new HashMap<>();
    Map<String, Set<String>> characterToComic = new HashMap<>();
    Set<String> characters = new HashSet<>();
    BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
    try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null && line < rowsToLoad) {
            line++;
            String comicBook = nextLine[1];
            String[] characterNames = nextLine[0].split("/");
            if (!comicToCharacter.containsKey(comicBook)) {
                comicToCharacter.put(comicBook, new HashSet<String>());
            }
            List<String> comicCharacters = Arrays.asList(characterNames);
            comicToCharacter.get(comicBook).addAll(comicCharacters);
            characters.addAll(comicCharacters);

        }
    }

    for (String character : characters) {
        creationQueue.add(new CharacterCreationCommand(character, graph));
    }

    BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
    for (String comicBook : comicToCharacter.keySet()) {
        creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
        Set<String> comicCharacters = comicToCharacter.get(comicBook);
        for (String character : comicCharacters) {
            AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
            appearedQueue.add(lineCommand);
            if (!characterToComic.containsKey(character)) {
                characterToComic.put(character, new HashSet<String>());
            }
            characterToComic.get(character).add(comicBook);
        }
        REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
    }

    int maxAppearances = 0;
    String maxCharacter = "";
    for (String character : characterToComic.keySet()) {
        Set<String> comicBookSet = characterToComic.get(character);
        int numberOfAppearances = comicBookSet.size();
        REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
        if (numberOfAppearances > maxAppearances) {
            maxCharacter = character;
            maxAppearances = numberOfAppearances;
        }
    }
    LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);

    ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i = 0; i < POOL_SIZE; i++) {
        executor.execute(new BatchCommand(graph, creationQueue));
    }
    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + creationQueue.size());
        if (report) {
            REPORTER.report();
        }
    }

    executor = Executors.newSingleThreadExecutor();
    executor.execute(new BatchCommand(graph, appearedQueue));

    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + appearedQueue.size());
        if (report) {
            REPORTER.report();
        }
    }
    LOG.info("MarvelGraphFactory.load complete");
}

From source file:net.yacy.cora.storage.Files.java

public static BlockingQueue<String> concurentLineReader(final File f) throws IOException {
    final BlockingQueue<String> q = new LinkedBlockingQueue<String>();
    final InputStream is = read(f);
    final BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    Thread t = new Thread() {
        @Override/*from  w  ww  .j a v  a2s  . c o m*/
        public void run() {
            Thread.currentThread().setName("Files.concurrentLineReader:" + f);
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    q.put(line);
                }
            } catch (final IOException e) {
            } catch (final InterruptedException e) {
            } finally {
                try {
                    q.put(POISON_LINE);
                    try {
                        br.close();
                        is.close();
                    } catch (final IOException ee) {
                    }
                } catch (final InterruptedException e) {
                    // last try
                    q.add(POISON_LINE);
                    try {
                        br.close();
                        is.close();
                    } catch (final IOException ee) {
                    }
                }
            }
        }
    };
    t.start();
    return q;
}