Java:关于克隆方法的问题

发布于 2025-01-03 16:11:42 字数 167 浏览 3 评论 0原文

我在采访中被问到这些问题。

  1. 我们需要在并发环境中处理克隆方法吗?我们可以同步克隆方法吗?

  2. 在单例类中使用克隆方法有意义吗?

采访中我对此并没有给出令人信服的答案。

I got these asked in an interview.

  1. Do we need to take care of clone method in a concurrent environment ? Can we synchronize the clone method ?

  2. Does it make any sense to use clone method in singleton classes ?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

污味仙女 2025-01-10 16:11:42
  1. 可能 99.99% 的情况下是这样,但您只需像类的任何其他方法一样考虑克隆,并根据您的具体上下文在必要时同步它。同步其基类中未同步的方法没有任何问题。另一方面,在重写同步方法时不同步方法可能是一个错误,即使代码编译良好并且没有发出警告......

  2. 令人信服的答案可能是“否”关于单例设计模式的几句话。

  1. 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...

  2. A convincing answer would probably be NO with a couple of words on the singleton design pattern.

耳根太软 2025-01-10 16:11:42
  1. 如果您正在克隆一个在其他线程中可能发生更改的对象,那么您可能需要获取某种[读]锁,就像您对其执行任何其他操作一样。理论上,如果新对象可能受到不安全发布的影响(我建议不要不安全地发布可变对象!),则需要对新对象进行锁定。

  2. 如果您可以创建它的另一个实例,它就不会是单例(有单态反模式,它类似于单例反模式,只是更糟,并且可能会出于没有明确目的而涉及多个对象)。我猜如果您要子类化某个实现了 Cloneable 的类,您想要重写 clone 并可能抛出 CloneNotSupportedException 或返回 this.

  1. 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!).

  2. 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 override clone and either throw CloneNotSupportedException is possible or otherwise return this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文