Assume the following class is a singleton
public class myDAO {
//determines the tableName and Id column names to based on itemType
private String itemType;
public void setItemType(String itemType) {...}
//Following methods use itemType to customize their queries
public boolean findObj(int id){...}
public boolean deleteObj(int id){...}
public boolean updateObj(Obj obj){...}
//etc...
}
The code was recently refactored with the setter, thus giving the DAO some state. I’m seeing that this is configured as singleton-scope in Spring’s config file. I have a strange feeling that this could lead to potential race conditions. Is that correct?
I’m really not sure if this is indeed the case but it’d be a nightmarish situation to figure it out, IMHO if it were true. I know this may not be the best possible design but I just wanted to know if this could lead to race conditions when concurrent threads are querying for different itemTypes. I was thinking of changing the scope to prototype but am not sure if it’s indeed required in this case.
If multiple threads are calling
setItemType(...)and then callingfindObj(...)and are expecting to find the object with an id and with the item-type then yes, your strange feeling is correct, this is a potential race condition and won’t work in a multi-threaded application.You should instead pass in the
itemTypeto each of your methods:If the itemType is set just once after the DAO has been constructed by Spring then this is okay but should be done as part of your Spring configuration which is done single-threaded.
If you have to add an
itemTypeargument to all or most of the methods then it seems to me that you no longer should have a singleton. Instead you should consider having a DAO factory or something and have multiple DAO instances, each with their own item-type.