Java (Android) - Synchronized Queue and sending data -
i've 2 threads. 1 generating data, sec sending them server. classic producer-consumer situation? i've constructed simple code managing synchronised queue - hope: did more or less correct? reply me, please? code 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) { homecoming packets.get(position); } public synchronized int number_of_element_of_queue() { homecoming packets.size(); }
first thread add together new info putting them using simple command:
add_to_queue("xyz);
second 1 sending info in loop:
while (ok) { seek { while (number_of_element_of_queue()>0) { out.write(read_from_queue(0)+"\n"); out.flush; del_from_queue(0); // if no error delete sent element } } grab (ioexception e1) { reconnect(); } }
i think wrong because sending static info (simple static text instead of reading "queue") doesn't result in reconnection (i.e. after grab (ioexception e1) ). when utilize presented code, happens often, after reconnection. several times (send data, reconnect, send more data, 1 time again reconnect , on).
yeah, happens if queue empty? don't seem checking or handling it. not status not accounting for.
more generally, implementation shown not how queue works. queues first-in-first-out, no need position parameter. there not concept of "read" "delete", operations atomic via "take". best served using existing blockingqueue
implementation opposed writing own.
java android queue synchronized
No comments:
Post a Comment