Instance methods and thread-safety of instance variables

前端 未结 6 743
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:44

    There are many situations in which an instance may be accessible from multiple classes. For example, if your instance is a static variable in another class, then all threads would share that instance, and you can get into big trouble that way. That's just the first way that pops into my mind...

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-30 23:51

    'Instance Variables are not thread safe' - this statement depends on the context. It is true, if for example you are talking about Servlets. It is because, Servlets create only one instance and multiple threads access it. So in that case Instance Variables are not thread safe.

    In the above simplified case, if you are creating new instance for each thread, then your instance variables are thread safe.

    Hope this answers your question

    0 讨论(0)
  • 2021-01-30 23:56

    Each instance has its own set of instance variables. How would you detect whether every instance had a distinct "copy" of the methods? Wouldn't the difference be visible only by examining the state of the instance variables?

    In fact, no, there is only one copy of the method, meaning the set of instructions executed when the method is invoked. But, when executing, an instance method can refer to the instance on which it's being invoked with the reserved identifier this. The this identifier refers to the current instance. If you don't qualify an instance variable (or method) with something else, this is implied.

    For example,

    final class Example {
    
      private boolean flag;
    
      public void setFlag(boolean value) {
        this.flag = value;
      }
    
      public void setAnotherFlag(Example friend) {
        friend.flag = this.flag;
      }
    
    }
    

    There's only one copy of the bytes that make up the VM instructions for the setFlag() and setAnotherFlag() methods. But when they are invoked, this is set to the instance upon which the invocation occurred. Because this is implied for an unqualified variable, you could delete all the references to this in the example, and it would still function exactly the same.

    However, if a variable is qualified, like friend.flag above, the variables of another instance can be referenced. This is how you can get into trouble in a multi-threaded program. But, as long as an object doesn't "escape" from one thread to be visible to others, there's nothing to worry about.

    0 讨论(0)
  • 2021-01-31 00:00

    Issues with multi-threading arise primarily with static variables and instances of a class being accessed at the same time.

    You shouldn't worry about methods in the class but more about the fields (meaning scoped at the class level). If multiple references to an instance of a class exist, different execution paths may attempt to access the instance at the same time, causing unintended consequences such as race conditions.

    A class is basically a blueprint for making an instance of an object. When the object is instantiated it receives a spot in memory that is accessed by a reference. If more than one thread has a handle to this reference it can cause occurrences where the instance is accessed simultaneously, this will cause fields to be manipulated by both threads.

    0 讨论(0)
  • 2021-01-31 00:05

    A method is nothing but a set of instructions. Whichever thread calls the method, get a copy of those instructions. After that the execution begins. The method may use local variables which are method and thread-scoped, or it may use shared resources, like static resources, shared objects or other resources, which are visible across threads.

    0 讨论(0)
提交回复
热议问题