I’ve written the following code, but I feel I’m going wrong somewhere:
public class ProcessQueue {
static BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
public ProcessQueue() {
process();
}
public void add(String message) throws InterruptedException {
System.out.println("Added Queue size:" + queue.size());
System.out.println("Locked by Producer");
queue.put(message);
System.out.println("Lock Released by Producer");
}
public static void process() {
new Thread() {
@Override
public void run() {
try {
while (true) {
System.out.println("Locked by Consumer");
Message.send(queue.take());
System.out.println("Locked Released by Consumer");
System.out.println("Consuming Queue size:" + queue.size());
}
} catch (Exception ex) {
System.out.print(ex.getMessage());
}
}
}.start();
}
}
Here add(String) adds the string to the queue. It is called whenever it receives an input from a UDP port. process() processes the queue and sends it for processing to the class Message. The output Locked and Released Print Statements is not in the desired order.
EDIT
My expected answer should be:
if it’s in Producer that is add then Locked by Producer -> then add to Queue -> Lock Release. same way would be in consumer. But the operations shouldn’t interleave i.e. once locked by producer is printed it shouldn’t print locked by consumer and then release locks.
The only time blocking will occur here is on take when the queue is empty. Otherwise puts will continue to happen. So you may see the queue’s size not increment by one. You may want to put a bound on the LinkedBlockingQueue. Fyi the LBQ is default unbounded
Edit based on your edit:
My answer thus far is explaining what you are seeing and why. You are looking for a synchronous messaging passing queue. You can do this with the following:
SynchrnousQueue does exactly what you want. The Linked&ArrayBlockingQueue with a bound of 1 pretty much does the same. TransferQueue is a new queue offered in Java 7 which has
transfermethods that wait until a thread is ready to acquire.