Say I have a Resource
class which holds a Map
type resources
object:
public class Resource {
private Map<Integer, MyResource> resources = new HashMap<Integer, MyResource>();
public void addResource(MyResource r){
synchronized(resources){
resources.put(r.getId(), r);
}
}
public void removeResource(int id){
synchronized(resources){
resources.remove(id);
}
}
}
Since multiple threads could access the resources
, so I always use synchronized
block for adding new resource & removing existing resource like the code shows above.
Now, I would also like to add a function to get all the current resources, my question is very simple, that's should I use synchronized block too to return all the current resources or is it worthless to use synchronized block ?
public Map<Integer, MyResource> getResources(){
return resources;
}
Is it enough to use above code to return current resources, or is it still beneficial to use synchronized block as below:
public Map<Integer, MyResource> getResources(){
synchronized(resources){
return resources;
}
}
Personally, I feel that it doesn't worth to use synchronized block for getting resources since it always return the current moment resources. But I am not sure. So, it would be nice if you could explain to me the reason whether to use synchronized
block or not, thanks.