I have a producer consumer model which an arduino generates packets and inside my pc I have a java program which takes those packets and puts them into a BlockingQueue
. Now there are threads that process these packets.
Let's say X
is producer and A
, B
and C
are consumers thread. there is a queue which all consumers have reference to it. Messages(packets) are immutable objects (i.e. consumers can't change the state of the elements). My question is How can I know all threads are done with specific element inside queue so I can remove it?
here is my consumer run()
method:
@Override
public void run()
{
while (isStarted && !queue.isEmpty()) {
updateMap(queue.peek());
}
}
One design I'm thinking of is to use a bounded
queue. When producer finds out queue is full then it removes the first element. But I'm not sure if this is a safe approach. I read this tutorial and a few more and what I get is:
Producer should wait if Queue or bucket is full and Consumer should wait if queue or bucket is empty.
I'm sorry if it sounds obvious, but I'm new to multithread programming and the concurrency nature of code sounds scary to me.
EDIT:
All A
, B
and C
do independently. One is for Statistics one for updating network map etc.
EDIT 2:
As @Augusto sugested there is another approach which each of A
, B
and C
has their own queue. My network listener passes the packets to each queue and they process it. It works but How can I do this with only one queue? or is it possible to implement this scenario using only one queue? and if the answer is yes. How and when I need to remove element from queue?