弹簧注射-螺纹安全 [英] Spring Injection - Thread safe

查看:67
本文介绍了弹簧注射-螺纹安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test{
private First first;
private Second second;

public void setFirst(First first){
this.first = first;
}
public First getFirst(){
 return first;
}
// same approach for second
}

如果我通过弹簧注入来注入实例,它是线程安全的吗?如果没有,如何使其成为线程安全的?我搜寻了一下,发现矛盾的回应,无法得出任何结论。请提出建议。
提前谢谢。
-RW

If I inject the instance through spring injection, is it thread-safe? If not, how to make it thread-safe? I googled and found contradict responses, not able to come to any conclusion.Please suggest. Thanks in Advance. -RW

推荐答案

如果您在谈论我想说的话,那么这很有趣

If you're talking about what I think you're talking about, then it's an interesting discussion.

技术上,因为 setFirst() getFirst()不是同步的,那么它对于 setFirst()可能的。 c $ c>在线程1上注入一个对象,而 getFirst()在线程2上返回不同的对象。Java内存模型保留最终使该对象保留的权利。正如他们所说的那样。

Technically, because setFirst() and getFirst() are not synchronized, then it's possible for setFirst() to inject one object on Thread 1, and getFirst() to return a different object on Thread 2. The Java memory model reserves the right to make this "eventually consistent", as they say.

因此,对于Spring,它在启动(或服务器的内部启动线程)期间配置其bean图时,HTTP可能例如,由于缺少同步,请求线程将无法正确看到该bean图。

So in the case of Spring, which configures its bean graph during startup (or the server's internal startup thread), it's possible that the HTTP request threads (for example) would not see that bean graph properly, due to the lack of synchronization.

注意:这与并发访问无关。即使HTTP请求在Spring初始化之后出现,Java内存模型也不保证这些线程将看到正确的数据。

Note: this has nothing to do with concurrent access. Even if the HTTP requests come in after Spring has initialized, the Java memory model does not guarantee that those threads will see the correct data.

实际上,这永远不会发生(至少,我从未见过这种情况)。缺少同步只是并发线程真正的问题,在这里不是问题。

In practice, this never happens (at least, I've never seen it happen). The lack of synchronization is only really a problem for concurrent threads, which isn't the issue here.

因此,这实际上只是一个学术争论。

So it's really just an academic argument.

如果这不是您在说的,我深表歉意。不过,这仍然是一个有趣的想法。

If this isn't what you're talking about, my apologies. It's still an interesting thought, though.

这篇关于弹簧注射-螺纹安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆