I used this pattern to keep my code in Spring component thread safe:
@Configuration
public class MyConfig {
private volatile SSLContext cachedSSLContext;
public SSLContext getSSLContext() {
if (cachedSSLContext == null) {
synchronized (this) {
if (cachedSSLContext == null) {
cachedSSLContext = computeSSLContext();
}
}
}
return cachedSSLContext;
}
}
SonarQube considers this code buggy:
Non-primitive fields should not be “volatile”. Use a thread-safe type;
adding “volatile” is not enough to make this field thread-safe.
When I remove the volatile keyword, I receive another error “Double-checked locking ” in Idea with an intention “Make cachedSSLContext volatile”. So what to do now? Is SonarQube buggy because it does not read the code and just shouts?
1