Reputation: 2311
This is a design problem where I am trying to figure out in which level(application, class, object or even finer) I should put locks to ensure atomicity.
I have an application say Engine
which has a class A
and a method inside which contains a map.
class A{
public void methodA(){
Map<X,Y> testMap = Maps.newHashMap();
}
}
Now I have multiple threads accessing this map. What I want to ensure is atomic {read and write} combination on this map. Options which I have is
1.ConcurrentHashMap
2.Collections.synchronizedMap
3.static synchronizedMap outside the methodA
4.Application level locks using Redis or Memcache
What I should mention is I am considering the 4th option because the application Engine
can have multiple instances.
Now I am facing race conditions when multiple threads are trying to read and write to the map.
For option1 I get bucket level lock because different threads can be directed to different instances of the Engine
app
For option2 I get object level lock which faces the same issue as 1
For option3 I get class level lock which suffers from the same flaws of a multi instanced app
Option 4 seems the most viable option. However it will carry a performance overhead. So is there some way in Java to ensure this lock at a class level and not allow threads to modify different instances of the app.
With reference to Chetan's comment this local map is later used to talk to the dao of a database which is global and thats where the race condition is encountered.
Upvotes: 1
Views: 68
Reputation: 303
ConcurrentHashMap
even though all operations are thread-safe when you are 'get'ing, it may or may not reflect the 'put's.
Collections.synchronizedMap
Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency. use this option only if each thread needs to have an up-to-date view of the map
static synchronizedMap outside the methodA
same as 3
Application level locks using Redis or Memcache
From what I understood from your question, only this option make sense.
This is my understanding about your requirement, correct me if I am am wrong, will update answer accordingly: -You have multiple instances (as in multiple instances residing in multiple JVMs) of 'engine' application. while persisting the map (which is local to each instances) into the database you have to avoid race condition
Upvotes: 1