I’ve two threads. One for generating data, second for sending them to server. Is this a classic producer-consumer situation?
To do this I’ve constructed simple code for managing synchronised queue – I hope: I did it more or less correct? Could somebody answer me, please? My code is here below:
public ArrayList<String> Packets;
public synchronized void add_to_Queue (String data) {
Packets.add(data);
}
public synchronized void del_from_Queue (int position) {
Packets.remove(position);
}
public synchronized String read_from_ Queue(int position) {
return Packets.get(position);
}
public synchronized int number_of_element_of_Queue() {
return Packets.size();
}
First thread add new data by putting them using simple command:
add_to_Queue("XYZ);
Second one sending data in a loop:
while (OK)
{
try
{
while (number_of_element_of_Queue()>0)
{
out.write(read_from_Queue(0)+"\n");
out.flush;
del_from_Queue(0); // if no error delete just sent element
}
}
catch (IOException e1)
{
reconnect();
}
}
I think something is wrong because sending static data (simple static text instead of reading it from my “Queue”) doesn’t result in reconnection (i.e. after catch (IOException e1) ). But when I use presented code, it happens very often, especially after reconnection. It does it several times (send some data, reconnect, send some more data, again reconnect and so on).
Yeah, what happens if the queue is empty? You don’t seem to be checking for that or handling it. But that is not the only condition you are not accounting for.
More generally, the implementation shown is not how a Queue works. Queues are first-in-first-out, no need for a position parameter. There is not a concept of “read” then “delete”, those operations are usually atomic via a “take”. You are best served by using an existing
BlockingQueueimplementation as opposed to writing your own.