Java: questions about the cloning method

I asked them in an interview.

  • Do we need to take care of the cloning method in a parallel environment? Can we synchronize the cloning method?

  • Does it make sense to use the clone method in singleton classes?

I did not have convincing answers for this during the interview.

+8
java clone concurrency singleton
source share
2 answers
  • Probably yes, 99.99% of the time, but you just need to think about the clone, like any other methods of your class, and synchronize it, if necessary, depending on your specific context. There is nothing wrong with synchronizing a method that is not synchronized in its base class. On the other hand, not synchronizing the method when overriding the synchronized one is probably an error , even if the code compiles and no warnings are issued ...

  • The convincing answer is likely to be NO with a few words in the singleton design pattern.

+2
source share
  • If you are cloning an object that can be modified in other threads, you probably need to acquire some kind of lock [read], just as if you were doing some other operation on it. Theoretically, you would need to lock a new object if it could be subjected to unsafe publishing (I suggest not publishing a mutable object is unsafe!).

  • It would not be a single if you could make another instance (there is a antistat of a monostat, which looks like a one-sided antipattern, only worse and can include several objects without any clear purpose). I think if you subclassed some class that Cloneable implemented, you want to override clone , and it's possible to either throw a CloneNotSupportedException , or otherwise return this .

+1
source share

All Articles