public class Service { private List<SomeType> _list = null; public static List<SomeType> GetSomeTypeList() { if (_list != null) return _list; List<SomeType> _temp = null; _temp = FunctionToGetSomeTypeValue(); _list = _temp; return _list; } } It's server code, GetSomeTypeList may be called by multiple requests (threads), the return result of FunctionToGetSomeTypeValue will be the same even in different thread, it's a static resource, but FunctionToGetSomeTypeValue may fail by return null. My intention is to get the resource when it's needed and try to get it every time it's called, unless it is a success. The question is when updating _list, _list = _temp, do I need to lock using lock(lockobj) {_list=_temp}?
if two threads are calling GetSomeTypeList(), and both goes to call FunctionToGetSomeTypeValue(), one is success, one is failed, the success one call _list=_temp first, failed one then assign _list=null. I'm fine with this case, because eventually _list will be in a good state, and all calls just return _list.
Thing I don't understand is if I don't use lock, is there any chance _list object be assigned a incorrect value (a unexpected value)? Not null, neither correct _temp with correct address.
so the actual question is, assume there's variable: static int Obj = 0;
- one thread is setting
Obj = 1; - another thread is setting
Obj = 2;
if there's no lock over setting of Obj, value of Obj should be either 1 or 2, won't be anything else, is that correct? what if Obj is a struct?
Is assignment of reference object (address) a atomic operation ? What about simple type object(int, struct)?
lock?