I am trying to process some messages that I get from an MQ infrastructure.I have two blocking queues,sharedQueue
and pubQueue
. The sharedqueue
gets filled up with the messages that I get from the MQ infrastructure as below.It will put the messages to sharedQueue
.
client.setCallback(new CallBack("inst", sharedQueue));
The messagemanipulator thread will read from the sharedQueue
, process it and put the response to pubQueue
for later publishing.
new MessageManipulatorThread(sharedQueue,pubQueue).run();
The publisher thread will take messages from pubQueue
and publish it to the MQ infrastructure.
new PublisherThread(pubQueue).run();
Below is the full code :
public class ArrayBlockingQueueExample {
private BlockingQueue<String> sharedQueue = new ArrayBlockingQueue<>(64);
private BlockingQueue<String> pubQueue = new ArrayBlockingQueue<>(64);
public static void main(String[] args) throws MqttException, Exception {
new ArrayBlockingQueueExample().startThreads();
}
public void startThreads() throws MqttException, Exception{
MqttClient client = new MQTTClientFactory().getInstance();
client.setCallback(new CallBack("inst", sharedQueue));
new MessageManipulatorThread(sharedQueue,pubQueue).run();
new PublisherThread(pubQueue).run();
}
public MessageManipulatorThread( BlockingQueue<String> sharedQueue , BlockingQueue<String> pubQueue){
this.sharedQueue = sharedQueue;
this.pubQueue = pubQueue;
}
public void run() {
while (true) {
try {
String msg = sharedQueue.take();
System.out.println(Thread.currentThread().getName() + "manipulator runnning => "+msg);
pubQueue.put(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class PublisherThread implements Runnable {
private BlockingQueue<String> sharedQueue;
public PublisherThread(BlockingQueue<String> sharedQueue){
this.sharedQueue = sharedQueue;
}
public void run() {
while (true) {
System.out.println("Running pub");
try {
System.out.println("pub=>"+sharedQueue.take() );
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The problem is new PublisherThread(pubQueue).run();
never works.I am guessing this is a thread synchronization issue.The pubQueue
is supposed to wait till it has any data filled up by the MessageManipulatorThread
, but it doesnt look like that.The PublisherThread
is waiting upon the pubQueue
to be free, but it never becomes free ! , is there anything else I should do for this ? Any help is much appreciated.