NPE in an impossible place

86 Views Asked by At

I'm having this super weird NPE:

Technical Exception : stack error #java.lang.NullPointerException at packagename.addTraceIdToThreadContext(XXX.java:115) at ...

111    public void addTraceIdToThreadContext(String traceId) {
      ...
114        if (nonNull(this.logContext)) {
115            this.logContext.setTraceId(traceId);
116        }
117    }

(Thanks for the comments, the XXX.java is in singleton, the web app is under JBoss, nonNull method is imported from Objects class)

I suppose the line number in the stacktrace is correct? Any idea please? Thanks

1

There are 1 best solutions below

2
henriwang On

Thanks to @tgdavies, I found the reason.

In the same class there's a method which can set the logContext to null:

    public static SmaUtils getInstance(String moduleName) {
    ((SmaUtilsImpl) INSTANCE).logContext = null;
    ((SmaUtilsImpl) INSTANCE).moduleName = moduleName;
    return INSTANCE;
}

A second thread set the logContext to null while the first thread arrives between these 2 lines:

114 if (nonNull(this.logContext)) {
115     this.logContext.setTraceId(traceId);

The solution would be synchronized it but I'll review the code why we have this method which set the logContext to null.