List of usage examples for java.util.concurrent ArrayBlockingQueue poll
public E poll()
From source file:Main.java
public static void main(String[] argv) throws Exception { int capacity = 10; ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); for (int i = 0; i < 10; i++) { queue.add(i);//from w ww . j a va 2 s . c o m } System.out.println(queue.poll()); }
From source file:org.apache.nifi.processors.standard.util.TestPutTCPCommon.java
private void checkNoDataReceived(final ArrayBlockingQueue<List<Byte>> recvQueue) throws Exception { Thread.sleep(DATA_WAIT_PERIOD); assertNull(recvQueue.poll()); }
From source file:org.apache.nifi.processors.standard.util.TestPutTCPCommon.java
private void checkEmptyMessageReceived(final ArrayBlockingQueue<List<Byte>> recvQueue) throws Exception { Thread.sleep(DATA_WAIT_PERIOD); assertEquals(0, recvQueue.poll().size()); }
From source file:org.kchine.rpf.db.MainNodeManager.java
private static void createTask() { try {/* ww w . j a v a2 s.c om*/ System.out.println(" create worker round at " + new Date()); long T1 = System.currentTimeMillis(); final ArrayBlockingQueue<String> indexesQueue = new ArrayBlockingQueue<String>(200); Vector<NodeDataDB> nodes = _registry.getNodeData(""); for (int i = 0; i < nodes.size(); ++i) { final String nodeName = nodes.elementAt(i).getNodeName(); String nodeIp = nodes.elementAt(i).getHostIp(); String nodePrefix = nodes.elementAt(i).getPoolPrefix(); Vector<HashMap<String, Object>> servants = _registry.getTableData("SERVANTS", "NODE_NAME='" + nodeName + "'" + " OR (HOST_IP='" + nodeIp + "' AND NAME like '" + nodePrefix + "%')"); final int missing = nodes.elementAt(i).getServantNbrMin() - servants.size(); if (missing > 0) { System.out.println("Node<" + nodeName + "> missing :" + missing); for (int j = 0; j < missing; ++j) { indexesQueue.add(nodeName); } } } Thread[] t = new Thread[10]; for (int i = 0; i < t.length; ++i) { t[i] = new Thread(new Runnable() { public void run() { while (true) { if (indexesQueue.isEmpty()) break; try { if (_nodeData == null) { if (!indexesQueue.isEmpty()) { String nodeName = indexesQueue.poll(); if (nodeName != null) { try { _registry.lookup( System.getProperty("node.manager.name") + '_' + nodeName); } catch (NotBoundException nbe) { NodeManager _manager = (NodeManager) _registry .lookup(System.getProperty("node.manager.name")); ManagedServant ms = _manager.createServant(nodeName); System.out.println(ms + " successfully created"); } } } } else { if (!indexesQueue.isEmpty()) { String nodeName = indexesQueue.poll(); if (nodeName != null && nodeName.equals(_nodeData.getNodeName())) { NodeManager _manager = (NodeManager) _registry.lookup(_nodeManagerName); ManagedServant ms = _manager.createServant(nodeName); System.out.println(ms + " successfully created"); } } } } catch (Exception e) { e.printStackTrace(); } finally { try { Thread.sleep(500); } catch (Exception e) { } } } } }); t[i].start(); } for (int i = 0; i < t.length; ++i) { t[i].join(); } System.out .println("Last create servants round took :" + (System.currentTimeMillis() - T1) + " millisec"); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.nifi.processors.standard.util.TestPutTCPCommon.java
private void checkReceivedAllData(final ArrayBlockingQueue<List<Byte>> recvQueue, final String[] sentData, final int iterations) throws Exception { // check each sent FlowFile was successfully sent and received. for (int i = 0; i < iterations; i++) { for (String item : sentData) { List<Byte> message = recvQueue.take(); assertNotNull(message);/*from ww w .ja v a2 s.co m*/ Byte[] messageBytes = new Byte[message.size()]; assertArrayEquals(item.getBytes(), ArrayUtils.toPrimitive(message.toArray(messageBytes))); } } runner.assertTransferCount(PutTCP.REL_SUCCESS, sentData.length * iterations); runner.clearTransferState(); // Check that we have no unexpected extra data. assertNull(recvQueue.poll()); }
From source file:org.kchine.r.server.RListener.java
public static String[] clusterApply(final String cl, final String varName, final String functionName, final String ato, final String asynch) { new Thread(new Runnable() { public void run() { try { Cluster cluster = _clustersHash.get(cl); if (cluster == null) { new Thread(new Runnable() { public void run() { try { DirectJNI.getInstance().getRServices() .consoleSubmit(convertToPrintCommand("Invalid cluster")); } catch (Exception e) { e.printStackTrace(); }/*ww w . j a v a2s . c o m*/ } }).start(); } RObject v = DirectJNI.getInstance().getRServices().getObject(varName); RObject vtemp = null; if (v.getClass() == RMatrix.class) { vtemp = ((RMatrix) v).getValue(); } else if (v.getClass() == RArray.class) { vtemp = ((RArray) v).getValue(); } else { vtemp = v; } final RObject var = vtemp; final VWrapper vwrapper = new VWrapper() { public int getSize() { if (var.getClass() == RNumeric.class) { return ((RNumeric) var).getValue().length; } else if (var.getClass() == RInteger.class) { return ((RInteger) var).getValue().length; } else if (var.getClass() == RChar.class) { return ((RChar) var).getValue().length; } else if (var.getClass() == RLogical.class) { return ((RLogical) var).getValue().length; } else if (var.getClass() == RComplex.class) { return ((RComplex) var).getReal().length; } else if (var.getClass() == RList.class) { return ((RList) var).getValue().length; } return 0; } public RObject getElementAt(int i) { if (var.getClass() == RNumeric.class) { return new RNumeric(((RNumeric) var).getValue()[i]); } else if (var.getClass() == RInteger.class) { return new RInteger(((RInteger) var).getValue()[i]); } else if (var.getClass() == RChar.class) { return new RChar(((RChar) var).getValue()[i]); } else if (var.getClass() == RLogical.class) { return new RLogical(((RLogical) var).getValue()[i]); } else if (var.getClass() == RComplex.class) { return new RComplex(new double[] { ((RComplex) var).getReal()[i] }, new double[] { ((RComplex) var).getImaginary()[i] }, ((RComplex) var).getIndexNA() != null ? new int[] { ((RComplex) var).getIndexNA()[i] } : null, ((RComplex) var).getNames() != null ? new String[] { ((RComplex) var).getNames()[i] } : null); } else if (var.getClass() == RList.class) { return (RObject) ((RList) var).getValue()[i]; } return null; } public Object gatherResults(RObject[] f) { if (var.getClass() == RList.class) { return f; } else { Class<?> resultClass = f[0].getClass(); RObject result = null; if (resultClass == RNumeric.class) { double[] t = new double[f.length]; for (int i = 0; i < f.length; ++i) t[i] = ((RNumeric) f[i]).getValue()[0]; result = new RNumeric(t); } else if (resultClass == RInteger.class) { int[] t = new int[f.length]; for (int i = 0; i < f.length; ++i) t[i] = ((RInteger) f[i]).getValue()[0]; result = new RInteger(t); } else if (resultClass == RChar.class) { String[] t = new String[f.length]; for (int i = 0; i < f.length; ++i) t[i] = ((RChar) f[i]).getValue()[0]; result = new RChar(t); } else if (resultClass == RLogical.class) { boolean[] t = new boolean[f.length]; for (int i = 0; i < f.length; ++i) t[i] = ((RLogical) f[i]).getValue()[0]; result = new RLogical(t); } else if (resultClass == RComplex.class) { double[] real = new double[f.length]; double[] im = new double[f.length]; for (int i = 0; i < f.length; ++i) { real[i] = ((RComplex) f[i]).getReal()[0]; im[i] = ((RComplex) f[i]).getImaginary()[0]; } result = new RComplex(real, im, null, null); } else { throw new RuntimeException( "Can't Handle this result type :" + resultClass.getName()); } return result; } } }; if (vwrapper.getSize() == 0) { new Thread(new Runnable() { public void run() { try { DirectJNI.getInstance().getRServices() .consoleSubmit(convertToPrintCommand("0 elements in data")); } catch (Exception e) { e.printStackTrace(); } } }).start(); } Vector<RServices> workers = cluster.getWorkers(); final ArrayBlockingQueue<Integer> indexesQueue = new ArrayBlockingQueue<Integer>( vwrapper.getSize()); for (int i = 0; i < vwrapper.getSize(); ++i) indexesQueue.add(i); final ArrayBlockingQueue<RServices> workersQueue = new ArrayBlockingQueue<RServices>( workers.size()); for (int i = 0; i < workers.size(); ++i) workersQueue.add(workers.elementAt(i)); final RObject[] result = new RObject[vwrapper.getSize()]; for (int i = 0; i < workers.size(); ++i) { new Thread(new Runnable() { public void run() { RServices r = workersQueue.poll(); while (indexesQueue.size() > 0) { Integer idx = indexesQueue.poll(); if (idx != null) { try { result[idx] = r.call(functionName, vwrapper.getElementAt(idx)); } catch (Exception e) { e.printStackTrace(); result[idx] = nullObject; } } } } }).start(); } while (true) { int count = 0; for (int i = 0; i < result.length; ++i) if (result[i] != null) ++count; if (count == result.length) break; Thread.sleep(100); } Object reconstituedObject = vwrapper.gatherResults(result); if (v.getClass() == RMatrix.class) { ((RArray) v).setValue((RVector) reconstituedObject); } else if (v.getClass() == RArray.class) { ((RArray) v).setValue((RVector) reconstituedObject); } else if (v.getClass() == RList.class) { ((RList) v).setValue((RObject[]) reconstituedObject); } else { v = (RObject) reconstituedObject; } final RObject final_v = v; new Thread(new Runnable() { public void run() { try { DirectJNI.getInstance().getRServices().putAndAssign(final_v, (ato.equals("") ? functionName + "_" + varName : ato)); DirectJNI.getInstance().getRServices().consoleSubmit( convertToPrintCommand("Cluster Apply result assigned to R variable " + (ato.equals("") ? functionName + "_" + varName : ato) + "\n")); } catch (Exception e) { e.printStackTrace(); } } }).start(); } catch (Exception e) { e.printStackTrace(); } } }).start(); return new String[] { "OK", convertToPrintCommand("Cluster Apply Submitted in background..") }; }
From source file:com.ibm.crail.tools.CrailBenchmark.java
void collectionTest(int size, int loop) throws Exception { System.out.println("collectionTest, size " + size + ", loop " + loop); RingBuffer<Object> ringBuffer = new RingBuffer<Object>(10); ArrayBlockingQueue<Object> arrayQueue = new ArrayBlockingQueue<Object>(10); LinkedBlockingQueue<Object> listQueue = new LinkedBlockingQueue<Object>(); Object obj = new Object(); long start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { ringBuffer.add(obj);/* ww w . j a va 2 s . c o m*/ Object tmp = ringBuffer.peek(); tmp = ringBuffer.poll(); } } long end = System.currentTimeMillis(); double executionTime = ((double) (end - start)); System.out.println("ringbuffer, execution time [ms] " + executionTime); start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { arrayQueue.add(obj); Object tmp = arrayQueue.peek(); tmp = arrayQueue.poll(); } } end = System.currentTimeMillis(); executionTime = ((double) (end - start)); System.out.println("arrayQueue, execution time [ms] " + executionTime); start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { listQueue.add(obj); Object tmp = listQueue.peek(); tmp = listQueue.poll(); } } end = System.currentTimeMillis(); executionTime = ((double) (end - start)); System.out.println("arrayQueue, execution time [ms] " + executionTime); }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore/*from w ww . ja v a 2 s. c o m*/ public void testReplicationQuorumLoss() throws Throwable { System.out.println("======================================"); System.out.println(" Start 2 ActiveMQ nodes."); System.out.println("======================================"); startBrokerAsync(createBrokerNode("node-1", port)); startBrokerAsync(createBrokerNode("node-2", port)); BrokerService master = waitForNextMaster(); System.out.println("======================================"); System.out.println(" Start the producer and consumer"); System.out.println("======================================"); final AtomicBoolean stopClients = new AtomicBoolean(false); final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100); final AtomicLong receivedCounter = new AtomicLong(); final AtomicLong sentCounter = new AtomicLong(); Thread producer = startFailoverClient("producer", new Client() { @Override public void execute(Connection connection) throws Exception { Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("test")); long actual = 0; while (!stopClients.get()) { TextMessage msg = session.createTextMessage("Hello World"); msg.setLongProperty("id", actual++); producer.send(msg); sentCounter.incrementAndGet(); } } }); Thread consumer = startFailoverClient("consumer", new Client() { @Override public void execute(Connection connection) throws Exception { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue("test")); long expected = 0; while (!stopClients.get()) { Message msg = consumer.receive(200); if (msg != null) { long actual = msg.getLongProperty("id"); if (actual != expected) { errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected); } msg.acknowledge(); expected = actual + 1; receivedCounter.incrementAndGet(); } } } }); try { assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); System.out.println("======================================"); System.out.println(" Master should stop once the quorum is lost."); System.out.println("======================================"); ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum. assertStopsWithin(master, 10, TimeUnit.SECONDS); assertNull(errors.poll()); // clients should not see an error since they are failover clients. stopped.add(master); System.out.println("======================================"); System.out.println(" Restart the slave. Clients should make progress again.."); System.out.println("======================================"); startBrokersAsync(createBrokerNodes(stopped)); assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { // Wait for the clients to stop.. stopClients.set(true); producer.join(); consumer.join(); } }