Skip to content

CT_CONSTRUCTOR_THROW: report violation for final fields #2984

@romani

Description

@romani

https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#ct-be-wary-of-letting-constructors-throw-exceptions-ct-constructor-throw

https://wiki.sei.cmu.edu/confluence/display/java/OBJ11-J.+Be+wary+of+letting+constructors+throw+exceptions

Final field. Declaring the variable that is initialized to the object as final prevents the object from being partially initialized. The compiler produces a warning when there is a possibility that the variable's object might not be fully initialized. Declaring the variable final also guarantees initialization safety in multithreaded code. According to The Java Language Specification (JLS), §17.5, "final Field Semantics" [JLS 2015], "An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields." In other words, when a constructor executing in one thread initializes a final field to a known safe value, other threads are unable to see the preinitialized values of the object.

detected at checkstyle/checkstyle#14475 (comment)
We have class that has all fields as final, so if we can trust this article in web, it should be affected by this Finalizer attacks.

can we skip violations on classes that have all fields as final?

Example: https://github.com/checkstyle/checkstyle/blob/9349abeaed8715e3f005b8ec26660738edd25846/src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java#L42

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions