javaconstructorerrorprone

Resolving error-prone ConstructorLeaksThis warning on constructors which call other constructors


We have a few classes with the usual pattern for sharing constructor logic:

public X(E... processors)
{
    this(ImmutableList.copyOf(processors));
}

public X(Collection<E> processors)
{
    this.processors = ImmutableList.copyOf(processors);
}

In this situation, error-prone complains with ConstructorLeaksThis

.../X.java:61: error: [ConstructorLeaksThis] Constructors should not pass the 'this' reference out in method invocations, since the object may not be fully constructed.
        this(ImmutableList.copyOf(processors));
        ^
    (see http://errorprone.info/bugpattern/ConstructorLeaksThis)

If this implementation pattern is actually unsafe, I'm sure it can be refactored out to static methods fairly easily, but I guess the question is, is is unsafe? Maybe this isn't what the compiler check intended to detect?


Solution

  • Error-prone defines ConstructorLeaksThis problem:

    During the execution of a constructor, it’s dangerous to make the new instance accessible to other code. Fields of the instance, including final fields, may not yet be initialized, and executing instance methods may yield unexpected results.

    ...And from your code, you're not violating the rule, also Java documentation wrote about Using this with a Constructor, it's a false positive, the same issue was reported here.

    BTW, you can add @SuppressWarnings("ConstructorLeaksThis") in your constructor to suppress the errors or refactor your code without @SuppressWarnings to prevent hidden bugs.