I am taking a look at Java’s delivered code for Deflater. I notice that all methods accessing the ZStreamRef object created natively are synchronizing access to it. For example:
public void setLevel(int level) {
if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) {
throw new IllegalArgumentException("invalid compression level");
}
synchronized (zsRef) {
if (this.level != level) {
this.level = level;
setParams = true;
}
}
}
Yet, the Javadoc does not mention that Deflater is thread safe. Is it a requirement to synchronize natively created objects before accessing them?
The documentation doesn’t state that it need to be thread safe, and it might not be thread safe on all platforms. However in the OpenJDK it is. Not sure it is very useful however as its stateful and would almost certainly require external locking to share the stream between threads. (Which I doubt is a good idea)