I'm trying to determine if I need to be worried about thread-safety in a few crucial classes I have written. I've read several articles/existing SO questions, and I keep seeing the same, recurring definition of thread-safety:
Thread Safety means that the fields of an object or class always maintain a valid state, as observed by other objects and classes, even when used concurrently by multiple threads.
OK. I kind of get it. But there's a very big piece of the puzzle I'm missing here:
Does thread-safety only come into play when the same instance of a class is being used by multiple threads, or just when any 2+ instances are being used?
Example #1:
Say I have a Dog
class that contains no static methods or fields, and let's say I have 5 different instances of a Dog
that are being operated on from inside 5 different threads. Do I need to be concerned about thread-safety? I would say "no", because there are no static fields/methods, and each thread has its own instance of Dog
whose state exists independently of the other 4 instances. (1) Is this correct? If not, why?
Example #2:
Now let's say I add a static method to Dog
:
public void woof() {
this.isWoofing = true;
}
public static void makeWoof(Dog dog) {
dog.woof();
}
Do I need to be concerned about thread-safety now? Each thread has its own instance of a Dog
, but now they are sharing the same static makeWoof()
method, which changes the state of the Dog
it is operating on. I still say "no". (2) Is this correct? If not, why?
Given these 2 examples, it seems to me that thread-safety is only an issue when multiple threads are operating on the same instance of a class. But the minute you give each thread its own instance, it seems that I can do anything I want to that instance and not worry about what's going on inside the other threads. (3) Is this correct? If not, why? Are they any exceptions to this? Thanks in advance!