Forums Register Login

Reading and writing to a Hashmap from other threads. Not sure how syncronizing works.

+Pie Number of slices to send: Send
(PLEASE answer in "little java words" for I am learning. <Very big smile)

In my main server thread it contains a queue (of out going packets) and a client ref hashmap with id's and the ref to each new client OBJ I create. Also, this same server generates a thread which handles the packets queue which then is distributed to the hashmaps (client ref).queues (probably more info then is needed for this question.)

Any who, I need my server dispatch thread to walk the client ref hashmap and plug in the packets into each client's queue.. this same hashmap is is added to each time a client connects.. (So I'm seeing a need to syncronize)

In the main server thread syncronizing the read and write methods to the hashmap is not how I want to do this right?

Somehow which I'm not sure of I need to syncronize my queue's and hashmap.

Anyone have a good article or some code snipets to explain how to do this.

Man I was so pleased with myself How well I was creating threads and having them work sending packets back and forth to my client. Then I started thinking....

P.S. I created a 1 does all method for my queues that I think is safe code listed below...








1
+Pie Number of slices to send: Send

1. hashmap is not synchronized so it must be operated in single thread environment.
2. if you want to use hashmap with more than one thread consider using synchronized hashmap or Concurrent hashmap.
3. you can get synchronized hashmap by calling Collections.synchronizedMap() method.

you may also find my blog post about How HashMap works in Java interesting.
+Pie Number of slices to send: Send
Thanks, I converted it to a list which seems to be working fine.

One related question, if I call anyone of the synchronized methods which work with the list in an object, all the other synchronized methods are blocked correct?

thanks in advance.
+Pie Number of slices to send: Send
 

joe vasher wrote:One related question, if I call anyone of the synchronized methods which work with the list in an object, all the other synchronized methods are blocked correct?



If they are synchronizing on the same object, then yes.
A lot of people cry when they cut onions. The trick is not to form an emotional bond. This tiny ad told me:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1053 times.
Similar Threads
Custom events and listeners using a queue event
Can I sit on ois.readObject() and wait for more packets? More questions
Fixed Thread Pools
Would writing my ownlock routines for hashmap and queue reads and writes be a better solution to syn
Reading and writing to a socket concurrently
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 10:18:01.