I have this class with 3 read methods and 1 write method:
class ResourceClass {
private static Map resourceMap = new HashMap();
// New method to update resource
public void write(String key, Object resource) {
resourceMap.put(key, resource);
}
public Object read(String var1) {
return resourceMap.get(var1);
}
public Object read(String var1, String var2) {
// .. Do task with var1 and var2
return resourceMap.get(var1);
}
public Object read(String var1, String var2, String var3) {
// .. Do task with var1, var2 and var3
return resourceMap.get(var1);
}
}
Currently, this class only contains a write and 3 read methods to consume the static resource. The problem with this configuration is that the only way to update the resourceMap
is to restart the application so the ResourceClass
is created again the resourceMap
is added to the class for its consumption.
What I want is to add some dynamic way to update resourceMap
without restarting the service, but for that I have to make this class Thread-Safe, in order to handle a write
method to update the resourceMap
safely. For this I have the option to use synchronized
keyword in read
and write
methods so only one thread has access to resourceMap
. This approach solves the problem, but includes others as well. These read
methods are high-concurrent methods so adding a synchronized
keyword will impact the service performance dramatically and surely we don't want that.
Does any body knows a way to keep the threads reading (not blocking each other) but when there comes one thread to write
all read
methods wait for the write to finish and resume when the write
finishes?