0

For instance,

public Foo{
    private Object mutex = new Object();
    private int bar;

    public Foo(Foo f){
        this.mutex = f.getMutex();
        this.bar = f.getBar();
    }

    public Object getMutex(){
        return mutex;
    }

    public void setBar(int bar){
        synchronized(mutex){
            this.bar = bar;
        }
    }

    public int getBar(){
        synchronized(mutex){
            return bar;
        }
    }
}
2
  • what is f (f.getMutex()) ?
    – Alex W
    Jul 9, 2012 at 18:50
  • 1
    Depends how you want the class to behave, but definitely make the mutex data member final.
    – wolfcastle
    Jul 9, 2012 at 18:52

2 Answers 2

3

It depends - do you want the two objects to share a mutex (a shallow copy, really) or do you want them to be independent? In most cases I'd expect the latter, in which case you wouldn't want to copy the reference.

1

In this case, should do all of the following:

  1. Make the mutex final
  2. Not copy the mutex
  3. Lock on the original instance's mutex during copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.