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()
.
If I don't synchronize this method I'll get wrong values?
-
14-06-2023 - |
Pergunta
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?
Solução 2
Outras dicas
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.
Extending the other answers, threads do not extend the Java language regarding visibility and scopes, only regarding the mode of execution of code, which means that values that only a single object can access or which are only valid locally are not needed to synchronize - only if values are being shared between multiple objects (static fields of a class, or a singleton instance where all accessors are getting returned the same object) synchronization gets worthy philosophizing about.