/** * @warn javadoc description missing * @warn param producer not described * @param producer */ public void setProducer(Producer producer) { long toRequest; boolean setProducer = false; synchronized (this) { toRequest = requested; p = producer; if (op != null) { // middle operator ... we pass thru unless a request has been made if (toRequest == Long.MIN_VALUE) { // we pass-thru to the next producer as nothing has been requested setProducer = true; } } } // do after releasing lock if (setProducer) { op.setProducer(p); } else { // we execute the request with whatever has been requested (or Long.MAX_VALUE) if (toRequest == Long.MIN_VALUE) { p.request(Long.MAX_VALUE); } else { p.request(toRequest); } } }
// 여러 쓰레드에서 하나의 object를 공유할 때 한 쓰레드가 해당 object를 사용하면 다른 쓰레드들은 사용이 종료될 때까지 기다려야 하는 경우 // wait()/notify()를 사용하면 된다. private void exampleWaitAndNotify() { Queue queue = new Queue(); Producer p = new Producer(queue); Consumer c = new Consumer(queue); p.start(); c.start(); }
public void testRedelivery() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_MOST_ONCE); p.send(msg()); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m1 = c.receive(); assertTrue(m1.getHeader().getFirstAcquirer().getValue()); assertFalse(m1.isSettled()); s.close(); s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m2 = c.receive(); m2.accept(); assertTrue(compareMessageData(m1, m2)); assertFalse(m2.getHeader().getFirstAcquirer().getValue()); assertNull(get(c)); conn.close(); }
/** * Request a certain maximum number of emitted items from the Observable this Subscriber is * subscribed to. This is a way of requesting backpressure. To disable backpressure, pass {@code * Long.MAX_VALUE} to this method. * * <p>Requests are additive but if a sequence of requests totals more than {@code Long.MAX_VALUE} * then {@code Long.MAX_VALUE} requests will be actioned and the extras <i>may</i> be ignored. * Arriving at {@code Long.MAX_VALUE} by addition of requests cannot be assumed to disable * backpressure. For example, the code below may result in {@code Long.MAX_VALUE} requests being * actioned only. * * <pre> * request(100); * request(Long.MAX_VALUE-1); * </pre> * * @param n the maximum number of items you want the Observable to emit to the Subscriber at this * time, or {@code Long.MAX_VALUE} if you want the Observable to emit items at its own pace * @throws IllegalArgumentException if {@code n} is negative */ protected final void request(long n) { if (n < 0) { throw new IllegalArgumentException("number requested cannot be negative: " + n); } Producer shouldRequest = null; synchronized (this) { if (p != null) { shouldRequest = p; } else if (requested == Long.MIN_VALUE) { requested = n; } else { final long total = requested + n; // check if overflow occurred if (total < 0) { requested = Long.MAX_VALUE; } else { requested = total; } } } // after releasing lock if (shouldRequest != null) { shouldRequest.request(n); } }
private void route(String consumerSource, String producerTarget, String routingKey, boolean succeed) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Consumer c = s.createConsumer(consumerSource, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); Producer p = s.createProducer(producerTarget, QoS.AT_LEAST_ONCE); AMQPMessage msg = msg(); AmqpValue sentinel = new AmqpValue(new AMQPDouble(Math.random())); msg.setAmqpValue(sentinel); Properties props = new Properties(); props.setSubject(new AMQPString(routingKey)); msg.setProperties(props); p.send(msg); if (succeed) { AMQPMessage m = c.receive(); assertNotNull(m); assertEquals(sentinel.getValue().getValueString(), m.getAmqpValue().getValue().getValueString()); m.accept(); } else { assertNull(get(c)); } c.close(); p.close(); conn.close(); }
public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); }
private static void calculateProducerPriorities() { getInstance().producersUnprioritied++; if (getInstance().producersUnprioritied == getInstance().producers) { getInstance().producersUnprioritied = 0; for (Producer c : getInstance().producersList) { c.setPriority(Thread.NORM_PRIORITY); } } }
public static <T> T produceLevelAware(int level, Producer<T> after, Producer<T> before) { T result = null; if (Build.VERSION.SDK_INT >= level) { if (null != after) result = after.produce(); } else { if (null != before) result = before.produce(); } return result; }
public void run() { producer.getReady(); MyBlockingQueue<Integer> buffer = producer.getBuffer(); Integer item = buffer.take(); while (item != null) { System.out.println(this + " fetches " + item + "."); Thread.yield(); item = buffer.take(); } }
// main for testing consumer/producer public static void main(String[] args) { // 한개의 버퍼를 생성후 이를 공유하는 두개의 스레드 : 소비자, 생성자를 동작 IntBuffer ib = new IntBuffer(); Consumer c = new Consumer(ib); Producer p = new Producer(ib); c.start(); p.start(); }
public static void main(String[] args) throws InterruptedException { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c); Consumer c1 = new Consumer(c); p1.start(); c1.start(); p1.join(); c1.join(); }
// 主程式 public static void main(String[] args) { // 建立執行緒物件 Producer producer = new Producer(); Consumer consumer = new Consumer(); // 啟動執行緒 producer.start(); consumer.start(); while (true) // 結束條件 if (producer.count >= MAXITEMS && producer.count == consumer.count) { isRunning = false; break; } }
public static void main(String[] args) throws InterruptedException { final int NUM = 10; Producer producer = new Producer(10); Consumer[] consumers = new Consumer[NUM]; for (int i = 0; i < NUM; i++) { consumers[i] = new Consumer(producer); } System.out.println("\t== START =="); producer.start(); for (int i = 0; i < NUM; i++) { consumers[i].join(); } System.out.println("\t== OVER =="); }
public MainTeset() throws Exception { QueueConsumer consumer = new QueueConsumer("queue"); Thread consumerThread = new Thread(consumer); consumerThread.start(); Producer producer = new Producer("queue"); for (int i = 0; i < 100000; i++) { HashMap message = new HashMap(); message.put("message number", i); producer.sendMessage(message); System.out.println("Message Number " + i + " sent."); } }
/** @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Producer product = new Producer(); Consumer consume = new Consumer(); ProducerConsumerQueue queue = new ProducerConsumerQueue(); boolean loops = true; while (loops) { System.out.println("please choose your option:\n1.Set menu\n2.Order\n3.Exit"); Scanner input = new Scanner(System.in); int choiceOfPizza = input.nextInt(); switch (choiceOfPizza) { case 1: product.start(); queue.put(product); loops = false; try { product.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("continue?(y/n)"); if (input.next().equalsIgnoreCase("y")) { loops = true; } break; case 2: consume.start(); queue.get(consume); loops = false; try { consume.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("continue?(y/n)"); if (input.next().equalsIgnoreCase("y")) { loops = true; } break; default: System.out.println("Thank you, see you again"); System.exit(1); break; } } }
public void setProducer(Producer p) { synchronized (this) { if (emitting) { missedProducer = p != null ? p : NULL_PRODUCER; return; } emitting = true; } boolean skipFinal = false; try { currentProducer = p; long r = requested; if (p != null && r != 0) { p.request(r); } emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }
/** * Create a fat pipe using the threads from the parent * * @param producer the producer * @param pool the group of pipes to add to */ public PooledFatPipe(Producer<T, S> producer, Pool pool, ExceptionListener listener) { this.producer = producer; this.listener = listener; this.pool = pool; name = producer.getClass().getSimpleName(); lock = new Semaphore(0); }
public void testRoundTrip() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); p.send(msg()); p.close(); // Settlement happens here Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m = c.receive(); m.accept(); assertEquals(1, m.getData().size()); assertEquals(data(), m.getData().get(0)); conn.close(); }
public void testReject() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); p.send(msg()); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m = c.receive(); m.reject(); assertNull(get(c)); conn.close(); }
private void routeInvalidTarget(String producerTarget) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); try { Producer p = s.createProducer(producerTarget, QoS.AT_LEAST_ONCE); p.close(); fail("Target '" + producerTarget + "' should fail"); } catch (Exception e) { // no-op } finally { conn.close(); } }
public void publish(byte[] event, String Id) throws ExecutionException, InterruptedException { logger.debug("Send message"); RecordMetadata m = kafkaProducer.send(new ProducerRecord<String, byte[]>("events", Id, event)).get(); System.out.println("Message produced, offset: " + m.offset()); System.out.println("Message produced, partition : " + m.partition()); System.out.println("Message produced, topic: " + m.topic()); }
private void decorationTest(DecorationProtocol d, Map<AMQPString, AMQPType> map) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); AMQPMessage msg = msg(); d.decorateMessage(msg, map); p.send(msg); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage recvMsg = c.receive(); recvMsg.accept(); compareMaps(map, d.getDecoration(recvMsg)); conn.close(); }
public static void main(String[] args) { Producer producer = new Producer(); Consumer consumer = new Consumer(); Point testPoint1 = new Point(2, 9); Point testPoint2 = new Point(2, 1); Point testPoint3 = new Point(5, 5); System.out.println( "When Point " + testPoint1.toString() + " was bidded, producer responded with " + producer.respondToBid(testPoint1).toString()); System.out.println( "When Point " + testPoint2.toString() + " was bidded, producer responded with " + producer.respondToBid(testPoint2).toString()); System.out.println( "When Point " + testPoint3.toString() + " was bidded, producer responded with " + producer.respondToBid(testPoint3).toString()); System.out.println( "When Point " + testPoint1.toString() + " was bidded, consumer responded with " + consumer.respondToBid(testPoint1).toString()); System.out.println( "When Point " + testPoint2.toString() + " was bidded, consumer responded with " + consumer.respondToBid(testPoint2).toString()); System.out.println( "When Point " + testPoint3.toString() + " was bidded, consumer responded with " + consumer.respondToBid(testPoint3).toString()); }
/** * Look for data from all the inputs * * @return true if data was consumed */ private boolean poll(Signal signal, Signal parent) { AtomicReferenceArray<T> o = outputs; for (int i = 0; i < o.length(); i++) { T input = o.getAndSet(i, null); if (input == null) continue; long seq = ++sequence; if (parent != null) parent.signal(); S product = producer.execute(input, reuseReceptors.get(i), signal); signal.signal(); if (!consume(product, seq, 0)) { Thread.yield(); if (!consume(product, seq, 0)) logger.info( "failed to consume product (" + product + ") from producer (" + producer + ")"); } producer.complete(product); return product != null; } return false; }
public void fragmentation(long FrameSize, int PayloadSize) throws UnsupportedProtocolVersionException, AMQPException, AuthenticationException, IOException { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.setMaxFrameSize(FrameSize); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); AMQPMessage msg = new AMQPMessage(); msg.addData(new Data(new byte [PayloadSize])); p.send(msg); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m = c.receive(); m.accept(); c.close(); assertEquals(PayloadSize, m.getData().get(0).getValue().length); conn.close(); }
synchronized void put(Producer product) { if (toBeOrNotToBe) { try { product.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } toBeOrNotToBe = false; }
public static void main(String[] args) { // TODO Auto-generated method stub BrokerService broker = new BrokerService(); try { broker.addConnector("tcp://localhost:61616"); broker.setPopulateJMSXUserID(true); broker.start(); if (broker.isPopulateJMSXUserID()) LOG.info("jmsxuserid is true"); else LOG.info("jmsxuserid is false"); Producer producer = new Producer(); LOG.info("Consumer created"); Consumer consumer = new Consumer("TestQueue"); producer.sendMessage("TestQueue", "hello buddy"); Thread.sleep(4000); } catch (JMSException e) { // TODO Auto-generated catch block LOG.debug("Error occured while sending message", e); } catch (Exception e) { // TODO: handle exception LOG.debug("error releasing resources", e); } }
@Override public void request(long n) { if (n < 0) { throw new IllegalArgumentException("n >= 0 required"); } if (n == 0) { return; } synchronized (this) { if (emitting) { missedRequested += n; return; } emitting = true; } boolean skipFinal = false; try { long r = requested; long u = r + n; if (u < 0) { u = Long.MAX_VALUE; } requested = u; Producer p = currentProducer; if (p != null) { p.request(n); } emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }
public class CommitterOperations { EntityManager em = Producer.getEntityManager(); EntityTransaction tx = em.getTransaction(); public Committer createCommit(Committer c) { em.persist(c); tx.commit(); em.clear(); return c; } }
public void testDataTypes() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); AMQPMessage msg = new AMQPMessage(); List<AMQPType> al = new ArrayList<AMQPType>(); al.add(new AMQPBoolean(true)); al.add(new AMQPByte(Byte.MAX_VALUE)); al.add(new AMQPChar(Character.CURRENCY_SYMBOL)); al.add(new AMQPDecimal64(BigDecimal.TEN)); al.add(new AMQPDouble(Double.NaN)); al.add(new AMQPInt(Integer.MIN_VALUE)); al.add(new AMQPNull()); al.add(new AMQPString("\uFFF9")); al.add(new AMQPSymbol(new String(new char[256]))); al.add(new AMQPTimestamp(Long.MAX_VALUE)); al.add(new AMQPUuid(System.currentTimeMillis(), Long.MIN_VALUE)); al.add(new AMQPUnsignedShort(0)); al.add(new AMQPArray(AMQPBoolean.FALSE.getCode(), new AMQPBoolean[]{})); al.add(new AmqpSequence(new ArrayList<AMQPType>())); AmqpSequence seq = new AmqpSequence(al); AmqpValue val = new AmqpValue(seq); msg.setAmqpValue(val); p.send(msg); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage recvMsg = c.receive(); recvMsg.accept(); assertEquals(val.getValue().getValueString(), recvMsg.getAmqpValue().getValue().getValueString()); conn.close(); }