How to avoid "Possible unsafe assignment to a non-final static field in a constructor" (AssignmentToNonFinalStatic)

My code currently suffers from "Possible unsafe assignment to a non-final static field in a constructor" (AssignmentToNonFinalStatic in PMD).

The class is written as a singleton class, the property affected by this warning looks like this

private static String myProperty;

and is filled by this construct:

public SystemPropertyUtils() throws ConfigException {
    someMethodThrowingConfigException();
    myProperty = "someValue" + this.someOtherValueFromAThreadSafeString;
}

Is there an elaborated way to negate this warning?


Solution 1:

Don't set static fields in the constructor. In this case, make the field, non-static.

Otherwise, I would have to suspect you don't need a constructor. Instead you can initialise the static field in a static initialiser block, or static method.