java - Synchronize on DataOutputStream -
i have gone through many tutorials on synchronization head spinning. have never understood :(.
i have java server(mainserver), when client connects creates new thread(serverthread) dataoutputstream.
the client talks serverthread , serverthread responds. every , mainserver distribute message clients utilizing each serverthread's dataoutputstream object.
i quite every , issue because both mainserver , serverthread trying send client @ same time. hence need lock on dataoutputstream object. life of me cannot understand concept further. every illustration read confusing.
what right way handle this?
serverthread's send client method:
public void replytoone(string reply){ seek { commandout.writeutf(reply); commandout.flush(); } grab (ioexception e) { logger.fatal("replytoone", e); } logger.info(reply); }
mainserver's distribute clients method:
public static void distribute(string broadcastmessage){ (map.entry<string, object[]> entry : accountinfolist.entryset()) { object[] tmpobjarray = entry.getvalue(); dataoutputstream temporarycout = (dataoutputstream) tmpobjarray[int_command_out]; //can grabbed while thread using seek { temporarycout.writeutf(broadcastmessage); temporarycout.flush(); } grab (ioexception e) { logger.error("distribute: writeutf", e); } logger.info(broadcastmessage); } }
i thinking should have in serverthread class.
public synchronized dataoutputstream getcommandout(){ homecoming commandout; }
is simple? know has been asked , answered, don't seem getting still, without individual help.
if me.....
i have linkedblockingqueue
on each client-side thread. then, each time client thread has moment of idleness on socket, checks queue. if there's message send queue, sends it.
then, server, if needs to, can add together items queue, and, when connection has space, sent.
add queue, have method on serverthread like:
addbroadcastmessage(mydata data) { broadcastqueue.add(data); }
and then, on socket side, have loop has timeout-block on it, breaks out of socket if idle, , just:
while (!broadcastqueue.isempty()) { mydata info = broadcastqueue.poll(); .... send data.... }
and you're done.
the linkedblockingqueue
manage locking , synchronization you.
java multithreading synchronization dataoutputstream
No comments:
Post a Comment