I'm writing Code for a Network Application. Therefor I'm using a LinkedBlockingQueue to store incoming messaged until they are consumed. The following code runs in it's own Thread and fills up the Queue:
while(true) {
String msg = in.readLine();
if(msg == null) continue;
recieveQueue.offer(msg);
System.out.println("recieveQueue.offer() called at: " + System.currentTimeMillis() + " hash:" + recieveQueue.hashCode());
System.out.println("Server recieved: " + msg.replace("\n", ""));
break;
}
Next I wrote a Method, which runs in the same "Main-Thread" (No extra Thread is created for this Method). It's only called when the stored Elements have to be consumed. It looks like the following:
public String recieveMessage() {
try {
System.out.println("recieveQueue.take() called at: " + System.currentTimeMillis() + " hash:" + recieveQueue.hashCode());
return recieveQueue.take();
}catch(InterruptedException e) {
e.printStackTrace();
return null;
}
}
When running this Code I get the following output:
recieveQueue.offer() called at: 1594558123030 hash:2091496189
Server recieved: CONFIRMED
recieveQueue.take() called at: 1594558123031 hash:2091496189
The hash verifies that I'm working on the same Queue, and as seen by the Time, recieveQueue.offer(msg) is definitely called before take() and so the Queue should contain a message. But the Program stops at the take() call. No Exceptions were thrown and there is no other point in the code where take() gets called. I waited for like 10 minutes but the take() call never finishes
Made few changes in your program.
Note: Please check in your code Consumer in while loop.
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main
{
public static void main(String[] args) {
BlockingQueue recieveQueue = new LinkedBlockingQueue<String>(10);
new Thread(){
public void run(){
int count=0;
while(true) {
count++;
String msg = "AAA:"+count;
if(msg == null) continue;
recieveQueue.offer(msg);
System.out.println("recieveQueue.offer() called at: " + System.currentTimeMillis() + " hash:" + recieveQueue.hashCode());
System.out.println("Server recieved: " + msg.replace("\n", ""));
}
}
}.start();
while(true){
try {
System.out.println("recieveQueue.take() called at: " + System.currentTimeMillis() + " hash:" + recieveQueue.hashCode());
System.out.println("recieveQueue.take() : "+recieveQueue.take());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.