Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8205910

diagnose use of 'this' with DU fields (for VTs and VBCs)



    • Type: Enhancement
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: repo-valhalla
    • Fix Version/s: repo-valhalla
    • Component/s: tools
    • Labels:


      In the standard syntax for constructors, both value types and object types risk exposing partially-constructed instances through misplaced use of the current object reference ('this') before the object is fully initialized and its invariants are all properly enforced.

      In the case of value types (which have all-final fields) and object types (such as value-based classes) which have one or more final fields, there is a particular check we can make to help prevent using 'this' before it is ready, by tracking the definite assignment status of fields (which is done anyway) and comparing that to the placement of uses of 'this' (either explicit or implicit).

      Here's an example of a VBC which which initializes two final fields and which exercises various uses (correct and buggy) of 'this' (both explicit and implicit).

      class VBC {
        private final int x, ymx;
        VBC(int x, int y) {
            //this.validate(); // BAD: DU = {x,ymx}
            ymx = y - x;
            //validate(); // BAD: DU = {x}
            this.x = x;
            validate(); //OK: DU = {}
            assert(this.x > 0); //OK: DU = {}
            assert(this.y() > 0); //OK: DU = {}
        int x() { return x; }
        int y() { return ymx + x; }
        void validate() {
           assert(x() > 0 && y() > 0);
        public static void main(String... av) {
            VBC z = new VBC(1, 10);
            assert(z.x() == 1);
            assert(z.y() == 10);

      Note that this VBC could just as well be a value type.

      The RFE is that the javac compiler should report a warning if any of the lines marked "BAD" is uncommented, on the grounds that 'this' is being used (other than a field reference) before all final fields are definitely assigned (i.e., before the DU set is empty).

      For compatibility, this must be a warning not an error for VBCs. But it can be an error for value classes, since they are all new code.


          Issue Links



              sadayapalam Srikanth Adayapalam
              jrose John Rose
              0 Vote for this issue
              2 Start watching this issue