实例方法和实例变量的线程安全性 [英] Instance methods and thread-safety of instance variables
问题描述
我想知道一个类的每个实例在该类中是否都有自己的方法副本?
I would like to known if each instance of a class has its own copy of the methods in that class?
可以说,我有以下课程MyClass
:
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){
...
}
}
因此,如果两个不同的用户创建MyClass
的实例,例如:
So if two differents users make an instance of MyClass
like:
MyClass instanceOfUser1 = new MyClass();
MyClass instanceOfUser2 = new MyClass();
是否知道每个用户在其线程中都有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?
我之所以问这个问题,是因为我经常读到实例变量不是线程安全的.当每个用户通过调用new
运算符获取实例时,我看不出为什么应该这样?
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?
推荐答案
每个对象都有自己的类实例变量的副本-它是在类的所有实例之间共享的static
变量.实例变量不一定是线程安全的,原因是它们可能会被多个调用非同步实例方法的线程同时修改.
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++;
}
}
现在,如果两个不同的线程同时调用increment
,那么您将面临数据竞争-在返回的两个方法结束时,instanceVariable
可能会增加1或2.您可以通过在increment
中添加synchronized
关键字,或使用AtomicInteger
而不是int
等来消除此数据争用,但这是因为每个对象都拥有自己的类实例的副本.变量不一定意味着以线程安全的方式访问变量-这取决于类的方法. (唯一的例外是final
不可变变量,它不能以线程不安全的方式进行访问,缺少像序列化黑客之类的愚蠢的东西.)
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.)
这篇关于实例方法和实例变量的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!