Eric Cochran
Eric Cochran

Reputation: 8574

Java volatile necessary with synchronized access?

In the following case, is volatile redundant? Would removing volatile make any difference here? Alternatively, would leaving volatile but removing the synchronized block and synchronized modifier make any difference here?

private volatile boolean registered;

synchronized boolean registered() {
  return registered;
}

void setRegistered(boolean registered) {
  synchronized (this) {
    this.registered = registered;
  }
}

Upvotes: 1

Views: 211

Answers (1)

markspace
markspace

Reputation: 11030

No, unless you have some other access that you have not shown, registered is fine without the volatile.

Removing volatile would speed up the code ever so slightly, I think. But I think the main benefit to removing volatile is it cleans up the code for a maintainer.

In this case, there's no difference between volatile and the synchronized methods that I can see, so use one or the other. (Except that the synchronized methods make the object you are using to guard the registered field public, which can be good and bad. A private volatile keeps the synchronization lock private.)


To try to clarify that last statement, if you have a class like this:

public class Reg {
    private boolean registered;

    synchronized boolean registered() {
      return registered;
    }

    void setRegistered(boolean registered) {
      synchronized (this) {
        this.registered = registered;
      }
    }
}

Which you then create a new instance of:

public class Test {
  public static Reg reg;
  public void static main( String... args ) {
     reg = new Reg();
     synchronized( reg ) {
            // do stuff
     }
  }
}

Anyone else trying to access reg.registered() while that lock in Test is held will block until said lock is released. The lock is public to anyone who can see the object. This can be good and bad. It lets other classes control access to your methods, which can be good for atomicity but it might also bake some thread control into a source-base, where it gets spread all over instead of just encapsulated by one class. Good and bad. There's probably other examples of why that can be good and bad, this is just one.

Upvotes: 2

Related Questions