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:io.orchestrate.client.itest.KvTest.java

@Theory
@org.junit.Ignore//from  w w w.  j  av  a 2  s.  c o  m
public void getKeyWithListenerAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));
    final BlockingQueue<KvObject> queue = DataStructures.getLTQInstance(KvObject.class);
    client.kv(collection(), key).get(String.class).on(new ResponseAdapter<KvObject<String>>() {
        @Override
        public void onFailure(final Throwable error) {
            fail(error.getMessage());
        }

        @Override
        public void onSuccess(final KvObject<String> object) {
            queue.add(object);
        }
    });

    @SuppressWarnings("unchecked")
    final KvObject<String> result = queue.poll(5000, TimeUnit.MILLISECONDS);
    // FIXME
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void purgeKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata obj = insertItem(key, "{}");

    final BlockingQueue<Boolean> queue = DataStructures.getLTQInstance(Boolean.class);
    client.kv(obj.getCollection(), obj.getKey()).delete(Boolean.TRUE).on(new ResponseAdapter<Boolean>() {
        @Override//from w w w  .j a va2 s  .  c  o m
        public void onFailure(final Throwable error) {
            fail(error.getMessage());
        }

        @Override
        public void onSuccess(final Boolean object) {
            queue.add(object);
        }
    });

    final Boolean result = queue.poll(5000, TimeUnit.MILLISECONDS);

    final KvObject<String> nullObj = client.kv(obj.getCollection(), obj.getKey())
            .get(String.class, obj.getRef()).get();

    assertNotNull(obj);
    assertTrue(result);
    assertNull(nullObj);
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void putKeyIfAbsentAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    thrown.expect(RuntimeException.class);

    final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class);
    client.kv(collection(), key).ifAbsent(Boolean.TRUE).put("{}").on(new ResponseAdapter<KvMetadata>() {
        @Override/*from  w  w  w  .j a va 2s. c  o m*/
        public void onFailure(final Throwable error) {
            fail(error.getMessage());
        }

        @Override
        public void onSuccess(final KvMetadata object) {
            queue.add(object);
        }
    });

    final KvMetadata kvMetadata = queue.poll(5000, TimeUnit.MILLISECONDS);

    final KvObject<String> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(String.class).get();

    assertNotNull(kvMetadata);
    assertNotNull(kvObject);
    assertEquals(kvMetadata.getCollection(), kvObject.getCollection());
    assertEquals(kvMetadata.getKey(), kvObject.getKey());
    assertEquals(kvMetadata.getRef(), kvObject.getRef());
    assertEquals("{}", kvObject.getValue());

    final KvMetadata kvMetadata2 = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .ifAbsent(Boolean.TRUE).put("{}").get();

    assertNull(kvMetadata2);
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void mergePatchKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    String name1 = Long.toHexString(RAND.nextLong());

    final KvMetadata kvMetadata = insertItem(key, "{`name1`:`%s`}", name1);

    String name2 = Long.toHexString(RAND.nextLong());

    final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class);

    client.kv(collection(), key).merge("{\"name2\":\"" + name2 + "\"}").on(new ResponseAdapter<KvMetadata>() {
        @Override//from  ww w. ja v a2s. co  m
        public void onFailure(final Throwable error) {
            fail(error.getMessage());
        }

        @Override
        public void onSuccess(final KvMetadata object) {
            queue.add(object);
        }
    });

    final KvMetadata patched = queue.poll(5000, TimeUnit.MILLISECONDS);

    assertNotEquals(kvMetadata, patched);

    final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(ObjectNode.class).get();

    assertEquals(patched.getRef(), kvObject.getRef());
    assertEquals(name1, kvObject.getValue().get("name1").asText());
    assertEquals(name2, kvObject.getValue().get("name2").asText());
}

From source file:org.apache.accumulo.core.clientImpl.ConditionalWriterImpl.java

@Override
public Iterator<Result> write(Iterator<ConditionalMutation> mutations) {

    BlockingQueue<Result> resultQueue = new LinkedBlockingQueue<>();

    List<QCMutation> mutationList = new ArrayList<>();

    int count = 0;

    long entryTime = System.currentTimeMillis();

    mloop: while (mutations.hasNext()) {
        ConditionalMutation mut = mutations.next();
        count++;/* w w  w.ja va  2s  .c  om*/

        if (mut.getConditions().size() == 0)
            throw new IllegalArgumentException(
                    "ConditionalMutation had no conditions " + new String(mut.getRow(), UTF_8));

        for (Condition cond : mut.getConditions()) {
            if (!isVisible(cond.getVisibility())) {
                resultQueue.add(new Result(Status.INVISIBLE_VISIBILITY, mut, null));
                continue mloop;
            }
        }

        // copy the mutations so that even if caller changes it, it will not matter
        mutationList.add(new QCMutation(mut, resultQueue, entryTime));
    }

    queue(mutationList);

    return new RQIterator(resultQueue, count);

}

From source file:org.apache.usergrid.tools.ImportAdmins.java

/**
 * Imports admin users./*from  w  w  w  .j a va 2 s .com*/
 *
 * @param fileName Name of admin user data file.
 */
private void importAdminUsers(final String fileName, final int writeThreadCount, final int auditThreadCount)
        throws Exception {

    int count = 0;

    File adminUsersFile = new File(importDir, fileName);

    logger.info("----- Loading file: " + adminUsersFile.getAbsolutePath());
    JsonParser jp = getJsonParserForFile(adminUsersFile);

    int loopCounter = 0;

    BlockingQueue<Map<String, Object>> workQueue = new LinkedBlockingQueue<Map<String, Object>>();
    BlockingQueue<Map<String, Object>> auditQueue = new LinkedBlockingQueue<Map<String, Object>>();

    startAdminWorkers(workQueue, auditQueue, writeThreadCount);
    startAdminAuditors(auditQueue, auditThreadCount);

    JsonToken token = jp.nextToken();
    validateStartArray(token);

    while (jp.nextValue() != JsonToken.END_ARRAY) {
        loopCounter += 1;

        @SuppressWarnings("unchecked")
        Map<String, Object> entityProps = jp.readValueAs(HashMap.class);
        if (loopCounter % 1000 == 0) {
            logger.debug("Publishing to queue... counter=" + loopCounter);
        }

        workQueue.add(entityProps);
    }

    waitForQueueAndMeasure(workQueue, writeEmptyCount, adminWriteThreads, "Admin Write");
    waitForQueueAndMeasure(auditQueue, auditEmptyCount, adminAuditThreads, "Admin Audit");

    logger.info("----- End: Imported {} admin users from file {}", count, adminUsersFile.getAbsolutePath());

    jp.close();
}

From source file:com.splout.db.qnode.QNodeHandlerContext.java

/**
 * Return a Thrift client to the pool. This method is a bit tricky since we may want to return a connection when a
 * DNode already disconnected. Also, if the QNode is closing, we don't want to leave opened sockets around. To do it
 * safely, we check whether 1) we are closing / cleaning the QNode or 2) the DNode has disconnected.
 * <p/>/*from www . j  a  v a2s  .  c  o  m*/
 * The given client never can be null.
 */
public void returnDNodeClientToPool(String dnode, DNodeService.Client client, boolean renew) {
    if (closing.get()) { // don't return to the pool if the system is already closing! we must close everything!
        if (client != null) {
            client.getOutputProtocol().getTransport().close();
        }
        return;
    }
    BlockingQueue<DNodeService.Client> dnodeQueue = thriftClientCache.get(dnode);
    if (dnodeQueue == null) {
        // dnode is not connected, so we exit.
        if (client != null) {
            client.getOutputProtocol().getTransport().close();
        }
        return;
    }
    if (renew) { // we have to try to renew the connection
        try {
            DNodeService.Client newClient = DNodeClient.get(dnode);
            if (client != null) {
                client.getOutputProtocol().getTransport().close();
                client = newClient;
            }
        } catch (TTransportException e) {
            // Was not possible to renew connection. We'll keep the broken one.
            log.warn("TTransportException while renewing client to dnode[" + dnode
                    + "]. Broken client is returned to the pool as is to continue.");
        }
    }
    try {
        dnodeQueue.add(client);
    } catch (IllegalStateException e) {
        client.getOutputProtocol().getTransport().close();
        log.error("Trying to return a connection for dnode [" + dnode
                + "] but the pool already has the maximum number of connections. This is likely a software bug!.");
    }

    // one last check to avoid not closing every socket.
    // here we avoid leaking a socket in case a close has happened in parallel or a DNode disconnected right in the
    // middle
    if (closing.get() || thriftClientCache.get(dnode) == null) {
        if (client != null) {
            client.getOutputProtocol().getTransport().close();
        }
    }
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void deleteKeyIfMatchAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata obj = insertItem("key", "{}");

    final BlockingQueue<Boolean> queue = DataStructures.getLTQInstance(Boolean.class);
    client.kv(obj.getCollection(), obj.getKey()).ifMatch(obj.getRef()).delete()
            .on(new ResponseAdapter<Boolean>() {
                @Override//ww  w . j a v  a 2  s.c o  m
                public void onFailure(final Throwable error) {
                    fail(error.getMessage());
                }

                @Override
                public void onSuccess(final Boolean object) {
                    queue.add(object);
                }
            });

    final Boolean result = queue.poll(5000, TimeUnit.MILLISECONDS);
    assertNotNull(obj);
    assertTrue(result);
}

From source file:org.apache.accumulo.core.client.impl.ConditionalWriterImpl.java

@Override
public Iterator<Result> write(Iterator<ConditionalMutation> mutations) {

    BlockingQueue<Result> resultQueue = new LinkedBlockingQueue<Result>();

    List<QCMutation> mutationList = new ArrayList<QCMutation>();

    int count = 0;

    long entryTime = System.currentTimeMillis();

    mloop: while (mutations.hasNext()) {
        ConditionalMutation mut = mutations.next();
        count++;/*from w  w  w .j av  a  2 s.com*/

        if (mut.getConditions().size() == 0)
            throw new IllegalArgumentException(
                    "ConditionalMutation had no conditions " + new String(mut.getRow(), UTF_8));

        for (Condition cond : mut.getConditions()) {
            if (!isVisible(cond.getVisibility())) {
                resultQueue.add(new Result(Status.INVISIBLE_VISIBILITY, mut, null));
                continue mloop;
            }
        }

        // copy the mutations so that even if caller changes it, it will not matter
        mutationList.add(new QCMutation(mut, resultQueue, entryTime));
    }

    queue(mutationList);

    return new RQIterator(resultQueue, count);

}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void purgeKeyIfMatchAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata obj = insertItem(key, "{}");

    final BlockingQueue<Boolean> queue = DataStructures.getLTQInstance(Boolean.class);
    client.kv(obj.getCollection(), obj.getKey()).ifMatch(obj.getRef()).delete(Boolean.TRUE)
            .on(new ResponseAdapter<Boolean>() {
                @Override/*from ww  w  .  j  ava 2  s  .c o  m*/
                public void onFailure(final Throwable error) {
                    fail(error.getMessage());
                }

                @Override
                public void onSuccess(final Boolean object) {
                    queue.add(object);
                }
            });

    final Boolean result = queue.poll(5000, TimeUnit.MILLISECONDS);

    final KvObject<String> nullObj = client.kv(obj.getCollection(), obj.getKey())
            .get(String.class, obj.getRef()).get();

    assertNotNull(obj);
    assertTrue(result);
    assertNull(nullObj);
}