Java Synchronization problem -- Chatting multiple chatroom applications -
I am developing a chat application. I have a function that processes chat messages. Each chat The room is identified by a unique shortcode Now I want to have a message waiting for the same shortcode when the message is being processed for a shortcode, while continuing to keep messages for other shortcodes needed. Please follow the peace of the code, what is the problem with it, as the messages of the same shortcode are being processed in parallel. I just can not guess the problem This block of code is executed outside any mute x, so many threads can run it at the same time, so each Threads (one shortcode) got its lock The simplest (but very efficient) way to fix this: In this way you have a lock according to a shortcode It is possible to use some such computational conventionshashmap as a more efficient method.
Private Hashmap
< / Lock> lock = lock; lock = lock.get (shortcode); if (lock == empty) {locks.put (shortcode,
Private Hashmop < String, Object & gt; Locks = new Hashmop & lt; String, Object & gt; (); Private Final Object hashmapLock = New Object (); Public Zero Handle ShortCode (string shortcode, string message, string to) {object lock = empty; Synchronize (hashap lock) {lock = lock.get (shortcode); If (lock == empty) {locks.put (shortcode, lock = new object ()); }} Synchronize (lock) {System.out.println ("Shortening Handling:" + Shortcode); // processing system.out.println ("handle successfully shortcode:" + shortcode + "......);}}
Comments
Post a Comment