SpongePowered/math

useless volatile

sunmisc opened this issue · 0 comments

in the Vector Matrix classes etc we can observe 2 fields

private transient volatile boolean hashed = false;
private transient volatile int hashCode = 0;

The reasons why we can safely remove volatile are:

  • Our primitives do aligned reading on all platforms (int 32 bit and boolean)

  • And the second, since we have all the fields of this class (x y z) immutable, therefore the race will not destroy anything for us

The solution, and yet you can step on a rake if you read from the heap several times, so we have to read 1 time, the final result of the hashCode should look like this:

@Override
public int hashCode() {
   int h = hashCode; // read only ONCE
   if (h == 0 && !hashed) {
       h = calc Hash code
       if (h == 0) {
           hashed = true;
       } else {
           hashCode = h;
       }
   }
   return h;
}

This will remove volatile on hashed and hashCode fields