简体   繁体   中英

Is super.clone() of Cloneable a thread safe method?

If I have a class Foo

public class Foo implements Serializable, Cloneable {
    public Foo() {}
    protected String s;
    protected int n;
    public Foo clone()  {
        return (Foo) super.clone();
    }
    public String getS() {
        return s;
    }
    public void setS(String s) {
        this.s = s;
    }
    public String getN() {
        return n;
    }
    public void setN(int n) {
        this.n = n;
    }
}

And it's used in MyClass and the handler is passed to two thread A and B what appens if at the same time thread A try to clone the handler and thread B try to change a public variable of the handler?
Eg

Foo Class
    s = "Hello"
    n = "42"

This class is passed to A and B that run at the same time.
A wants clone Foo Class and after 1 µs B wants change n to 43 .
The clone result will be s = "Hello" and n = "42" || n = "43" s = "Hello" and n = "42" || n = "43" ?
More simpler: super.clone() is thread safe or I have to use lock or synchronized ? In case I have to use lock or synchronized which is the best way to use them?

You are slightly misusing the term "thread-safe". It does not mean "synchronized", and that's apparently how you are using it. No amount of synchronization can prevent implementation errors from breaking thread safety. As an example, any code you wrote which mutates the object while not holding any lock will clearly violate thread safety of the object, and there is nothing a library method like Object.clone can do about that.

Ultimately, thread safety is always in the hands of the implementor and Object.clone() will not do anything to make that harder for you: all it does is read the state of the current object and copy it to the new object. It does not publish that new object.

clone is not specifically described as thread-safe, which means it's not. If one thread is cloning the object while another thread is changing it, the clone can end up in an inconsistent state.

You could grab a lock in your clone function, but much better would be to grab it in the code which calls clone .

No it is not thread safe if two threads are trying to execute this method over the same instance of Foo.

You should create a mutex using this instance .For example place the code which executes this clone method in synchronized(fooInstance) block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM