I would like to known if each instance of a class has its own copy of the methods in that class?
Lets say, I have following class MyClass
:
public MyClass { private String s1; private String s2; private String method1(String s1){ ... } private String method2(String s2){ ... } }
So if two differents users make an instance of MyClass
like:
MyClass instanceOfUser1 = new MyClass(); MyClass instanceOfUser2 = new MyClass();
Does know each user have in his thread a copy of the methods of MyClass
? If yes, the instance variables are then thread-safe, as long as only the instance methods manipulate them, right?
I am asking this question because I often read that instance variables are not thread-safe. And I can not see why it should be like that, when each user gets an instance by calling the new
operator?
Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately. As an example of a class that is not thread-safe, consider the RGBColor class, shown below.
An object that is created using a class is said to be an instance of that class. We will sometimes say that the object belongs to the class. The variables that the object contains are called instance variables. The methods (that is, subroutines) that the object contains are called instance methods.
Each object gets its own copy of the class's instance variables - it's static variables that are shared between all instances of a class. The reason that instance variables are not necessarily thread-safe is that they might be simultaneously modified by multiple threads calling unsynchronized instance methods.
Each object gets its own copy of the class's instance variables - it's static
variables that are shared between all instances of a class. The reason that instance variables are not necessarily thread-safe is that they might be simultaneously modified by multiple threads calling unsynchronized instance methods.
class Example { private int instanceVariable = 0; public void increment() { instanceVariable++; } }
Now if two different threads call increment
at the same then you've got a data race - instanceVariable
might increment by 1 or 2 at the end of the two methods returning. You could eliminate this data race by adding the synchronized
keyword to increment
, or using an AtomicInteger
instead of an int
, etc, but the point is that just because each object gets its own copy of the class's instance variables does not necessarily mean that the variables are accessed in a thread-safe manner - this depends on the class's methods. (The exception is final
immutable variables, which can't be accessed in a thread-unsafe manner, short of something goofy like a serialization hack.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With