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?
No, it is fine, as long as you don't use any shared variables. The bytes
and crc
are local per thread. That's why they are called local variables.
This is a static
method. Usually you need to worry about thread safety
when you're dealing with the state
of an object. For example, if you were changing values inside the CRC16
class itself, but you're not. Your function just takes an input bytes
and returns an output crc.getValue()
.
扩展其他答案,线程不扩展关于可见性和范围的Java语言,仅关于代码的执行模式,这意味着只需要一个对象可以访问的值或者只在本地有效的值不需要同步 - 仅如果在多个对象之间共享值(类的静态字段,或者所有访问者返回相同对象的单例实例),则同步值得哲学化。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.