I have a List with objects List<> my_objects. Several threads can change this list. Let’s suppose that I do not have any locking mechanism for controlling the access to the list.
What happens, if I’m working with an object of the list and suddenly another thread sets the array to null?
MyObject o = my_objects[i];
//now a second thread has set my_objects to null
o.myMethod();
Will a NullPointerException occur?
Furthermore, what happens if a second thread removes the considered object from the list while I’m working with it in the first thread?
//second thread:
//y = i
MyObject o2 = my_objects[y];
my_objects.Remove(o2);
That’s fine. The variable
my_objectsholds references to objects, not the objects themselves. When you make a new variableo, it holds a second reference to the same object. Then you clearmy_objects, which means you can’t refer to the actual object throughmy_objectsanymore. But that doesn’t change the fact that you still haveo, and you can still refer to the actual object througho. (And that in turn implies that the object itself still exists. C# is a garbage-collected language, which, to a first approximation means that objects are guaranteed to stick around until you’re done with them. Non-managed C++ is different in this respect, and Objective-C is different in yet a third way. Not that you asked.)Effectively, in this respect, references to
MyObjectbehave just like primitive types likeint. If I have an array ofint, and I dothen I can do whatever I want with
my_ints(clear it, remove items from it) and that won’t change the fact thatoistill exists.The thing about reference types like
MyObject, and the reason you got confused enough to ask this question, is that withMyObjectboth variables (oandmy_objects[i]) still refer to the same actual object, so if you mutate the object viamy_objects[i].gainSpiderPowers(), you’ll see the effects of that mutation no matter whether you’re looking viamy_objects[i]or viao.