Java:关于克隆方法的问题
我在采访中被问到这些问题。
我们需要在并发环境中处理克隆方法吗?我们可以同步克隆方法吗?
在单例类中使用克隆方法有意义吗?
采访中我对此并没有给出令人信服的答案。
I got these asked in an interview.
Do we need to take care of clone method in a concurrent environment ? Can we synchronize the clone method ?
Does it make any sense to use clone method in singleton classes ?
I did not have convincing answers for this during the interview.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能 99.99% 的情况下是这样,但您只需像类的任何其他方法一样考虑克隆,并根据您的具体上下文在必要时同步它。同步其基类中未同步的方法没有任何问题。另一方面,在重写同步方法时不同步方法可能是一个错误,即使代码编译良好并且没有发出警告......
令人信服的答案可能是“否”关于单例设计模式的几句话。
Probably yes 99.99% of the times but you just have to think at clone like any other methods of your class and synchronize it if necessary depending on your specific context. There is nothing wrong in synchronizing a method that is not synchronized in its Base class. On the other hand, not synchronizing a method while overriding a synchronized one is probably a mistake even if the code compiles fine and no warnings are issued...
A convincing answer would probably be NO with a couple of words on the singleton design pattern.
如果您正在克隆一个在其他线程中可能发生更改的对象,那么您可能需要获取某种[读]锁,就像您对其执行任何其他操作一样。理论上,如果新对象可能受到不安全发布的影响(我建议不要不安全地发布可变对象!),则需要对新对象进行锁定。
如果您可以创建它的另一个实例,它就不会是单例(有单态反模式,它类似于单例反模式,只是更糟,并且可能会出于没有明确目的而涉及多个对象)。我猜如果您要子类化某个实现了
Cloneable
的类,您想要重写clone
并可能抛出CloneNotSupportedException
或返回this
.If you are cloning an object which is subject to change in other threads, then you will probably need to acquire some sort of [read] lock just as if you were doing any other operation on it. Theoretically you would need a lock on the new object if it could ever be subject to unsafe publication (I suggest not publishing mutable object unsafely!).
It wouldn't be a singleton if you could make another instance of it (there is the monostate antipattern which is like the singleton antipattern, only worse and can involve multiple objects for no clear purpose). I guess if you were subclassing some class that implemented
Cloneable
you want to overrideclone
and either throwCloneNotSupportedException
is possible or otherwise returnthis
.