Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useless volatile #34

Open
sunmisc opened this issue Mar 3, 2022 · 0 comments
Open

useless volatile #34

sunmisc opened this issue Mar 3, 2022 · 0 comments

Comments

@sunmisc
Copy link

sunmisc commented Mar 3, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant