I have 2 Lists of differnt objects used in different contexts. Each list is accessed by multiple threads which can add, remove and change state of objects in list. Both lists are protected from multiple access by locking on the list. Thats seems fine.
There is now a requirement that objects in List1 holds a reference to an object in List2 in order to READ a particular property (which gets WRITEN by different threads).
So although each list (and hence contained objects) are each protected from multiple access it is now possible for one thread to write List1 Object1.Property while another thread is reading it via List2 Object2.Object1.Property.
Is this situation thead safe? (I don’t think it is but am not 100% sure).
If not safe – what is best way to make it safe?
I have 2 Lists of differnt objects used in different contexts. Each list is
Share
Then you should apply a lock directly on the written object. If you lock Object1 before modifying ‘Property’, then it will work no matter if the thread uses Object1.Property or Object2.Object1.Property.
As to know if it’s thread safe without locking, well it depends on the type of your property, and how you modify it. Read/Write operation are thread-safe on 32bit long data (for instance an int, or a reference). But your operation may need multiple Read/Write.