Java 中不同步的 getter/setter 行为
我有一个类作为另一个类的代表。
public class Delegate {
private AnotherClass ac;
public void delegateCall() {
this.ac.actualCall();
}
public void setAC(AnotherClass ac) {
this.ac = ac;
}
}
如果我有很多线程调用 delegateCall()
并且另一个线程调用 setAC()
,会产生什么后果?我的假设是,一些调用 delegateCall()
的线程将在设置之前访问 ac 实例,而另一些线程将在设置之后访问它。在我的特定应用程序中,每个线程获取哪个实例并不重要。
我的问题: JVM 中是否可能发生任何底层同步,可能导致调用 delegateCall() 的线程阻塞?
I have a class that serves as a delegate to another.
public class Delegate {
private AnotherClass ac;
public void delegateCall() {
this.ac.actualCall();
}
public void setAC(AnotherClass ac) {
this.ac = ac;
}
}
What are the ramifications if I have lots of threads calling delegateCall()
and another thread calls setAC()
? My assumption is that some of the threads calling delegateCall()
would get access to the ac instance before it was set and some would get access to it after it was set. In my particular application, it does not matter which instance each thread gets.
My question: Is there any underlying synchronization that may happen within the JVM that might cause the threads calling delegateCall() to block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这里没有任何东西可以阻挡。也没有什么可以保证“读取器”线程永远看到对
ac
的更改。实际上,几乎肯定会,但不能保证(因为您在此处显示的代码中不涉及“发生之前”障碍。当然,这可能适合您的情况。No, there's nothing that will block here. There's also nothing to guarantee that a "reader" thread will ever see the change to
ac
. In reality it almost certainly will, but it's not guaranteed (as there are no "happens-before" barriers involved in the code you've shown here. That may well be okay for your situation of course.在阅读了您的任务描述后,我认为您假设使用
对象池
会很有趣。正如乔恩所说,在您的代码中,没有什么可以阻止您获得 NullPointerException。
After reading the description of your task I think it'll be interesting for you to assume using
Objects Pool
.In your code, as Jon said, nothing prevents you from getting NullPointerException.