Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

java - Clarification on the meaning of the parameter block synchronization

i would like to know if this expression it is correct and if it means this: i put a write lock over the field status, and than i change it. If not, i would like to know what is the meaning of the paramenter, because i see always this.

public class Example {
    private int status;
    public Example(int status){
        this.status = status;
    }
    public void setStatus(int newStatus){
        synchronized(this.status){
            this.status = newStatus;
        }
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are several things wrong with this code:

  1. You cannot synchronize on a primitive.

    You could change it to an Integer but see below.

  2. Synchronizing on a non-final object is not a good idea.

    You could make it final

  3. Changing a field while it is being synchronized on is going to break in some very obscure ways. And now it is final it will not be allowed.

    Probably better to synchronize on another field.

  4. You should also provide a get method for completeness.

With all of these issue fixed your code looks something like this:

public class Example {
  private final Object statusLock = new Object();
  private Integer status;

  public Example(Integer status) {
    this.status = status;
  }

  public void setStatus(Integer newStatus) {
    synchronized (statusLock) {
      status = newStatus;
    }
  }


  public Integer getStatus() {
    return status;
  }
}

Now - with this code - the answer to your question is kind of. What happens here is that you lock all access to the status field through the set method from any other thread while you change it's value.

Notice that I do not synchronise in the get method. If I did then the above statement would change.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...