[英]If I don't synchronize this method I'll get wrong values?
public static int getCRC16(byte[] bytes) {
CRC16 crc = new CRC16();
crc.reset();
crc.update(bytes, 0, bytes.length);
return (int) crc.getValue();
}
Tons of threads will hit this method, if I don't synchronize I'll get a wrong crc
for a specific thread? 大量的线程会遇到这种方法,如果我不同步我会得到一个特定线程的错误的
crc
?
No, it is fine, as long as you don't use any shared variables. 不,没关系,只要你不使用任何共享变量。 The
bytes
and crc
are local per thread. bytes
和crc
是每个线程的本地。 That's why they are called local variables. 这就是为什么它们被称为局部变量。
This is a static
method. 这是一种
static
方法。 Usually you need to worry about thread safety
when you're dealing with the state
of an object. 通常,当您处理对象的
state
时,您需要担心thread safety
。 For example, if you were changing values inside the CRC16
class itself, but you're not. 例如,如果您正在更改
CRC16
类本身内部的值,但您不是。 Your function just takes an input bytes
and returns an output crc.getValue()
. 您的函数只接受输入
bytes
并返回输出crc.getValue()
。
扩展其他答案,线程不扩展关于可见性和范围的Java语言,仅关于代码的执行模式,这意味着只需要一个对象可以访问的值或者只在本地有效的值不需要同步 - 仅如果在多个对象之间共享值(类的静态字段,或者所有访问者返回相同对象的单例实例),则同步值得哲学化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.