This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes synchronization on a key in a collection, is this possible Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronization on a key in a collection, is this possible" Watch "synchronization on a key in a collection, is this possible" New topic
Author

synchronization on a key in a collection, is this possible

wayne forrest
Greenhorn

Joined: Aug 23, 2010
Posts: 17
Hi,

I need some help please, or suggestions on how to solve this problem.

I have data stored in a HashMap as below:

key1 ObjectA.
key2 ObjectB.
key3 ObjectC.

There is one producer per key and for example 100 users per key.

Currently I am synchronizing on the entire collection, and I guess this is not optimal, especially since Object(A/B/C) is going to change
very often, up to 5 times a second. And the clients really want the data as fast as possible.

Is it possible to sync on the KEY? is there perhaps a better collection to use?

Or what is the best way to solve this one without moving away from servlets?


thanks.





Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Your data structure choice depends on size and dynamics (add, find, remove, etc.)
that you don't describe. As for synchronization, all users of a referenced item must be
protected from untimely changes to that item. So if user37 reads or updates the object
referenced by Key1, user37 must synchronize on that object, not the entire data structure.
In addition, users that use or change the data structure must synchronize on it.

Jim ... ...


BEE MBA PMP SCJP-6
Madhan Sundararajan Devaki
Ranch Hand

Joined: Mar 18, 2011
Posts: 312

You may use java.util.concurrent.ConcurrentHashMap class instead.


S.D. MADHAN
Not many get the right opportunity !
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization on a key in a collection, is this possible
 
Similar Threads
Hashtables and Maps
Interface and Abstract Classes
how to write or map a primary key and two foreign key fields in one hbm.xml file
DuplicateKeyException for update method?
NX: Thread safe and WeakHashMap vs. Unrefence Interface