Java 中不同步的 getter/setter 行为

发布于 2024-08-24 01:39:20 字数 493 浏览 2 评论 0原文

我有一个类作为另一个类的代表。

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 技术交流群。

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

发布评论

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

评论(2

半衬遮猫 2024-08-31 01:39:20

不,这里没有任何东西可以阻挡。也没有什么可以保证“读取器”线程永远看到对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.

梦行七里 2024-08-31 01:39:20

在阅读了您的任务描述后,我认为您假设使用对象池会很有趣。

正如乔恩所说,在您的代码中,没有什么可以阻止您获得 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.

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