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

[Question] Can mutex() be simplified this way? #3381

Closed
qiutongs opened this issue Feb 8, 2019 · 4 comments
Closed

[Question] Can mutex() be simplified this way? #3381

qiutongs opened this issue Feb 8, 2019 · 4 comments

Comments

@qiutongs
Copy link

qiutongs commented Feb 8, 2019

private Object mutex() {
Object mutex = mutexDoNotUseDirectly;
if (mutex == null) {
synchronized (this) {
mutex = mutexDoNotUseDirectly;
if (mutex == null) {
mutexDoNotUseDirectly = mutex = new Object();
}
}
}
return mutex;
}

Basically, my confusion is why the local variable "mutex" is needed.

  private Object mutex() {
    if (mutexDoNotUseDirectly == null) {
      synchronized (this) {
        if (mutexDoNotUseDirectly == null) {
          mutexDoNotUseDirectly = new Object();
        }
      }
    }
    return mutexDoNotUseDirectly;
  }
@JakeWharton
Copy link

JakeWharton commented Feb 8, 2019 via email

@qiutongs
Copy link
Author

qiutongs commented Feb 8, 2019

@JakeWharton
Thank you for quick reply! Let me make sure I understand you correctly. The additional volatile read you meant is the one in the "return" statement in my code?

So the original code reads "mutexDoNotUseDirectly" on lines 190, 193, 195 (3 times in worst case). But my code reads "mutexDoNotUseDirectly" four times in worst case.

Is that the thing we try to optimize with the local variable?

@JakeWharton
Copy link

JakeWharton commented Feb 8, 2019 via email

@qiutongs
Copy link
Author

qiutongs commented Feb 8, 2019

It makes sense. Thank you!

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

No branches or pull requests

3 participants