Instance methods and thread-safety of instance variables

前端 未结 6 745
Happy的楠姐
Happy的楠姐 2021-01-30 23:40

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:

p         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 23:45

    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.)

提交回复
热议问题