Spring Boot中的每个异步调用是否会创建每个变量的单独副本?

发布于 2025-02-12 09:47:33 字数 510 浏览 0 评论 0原文

我想在这里澄清三个混乱。

问题1)我的第一个问题是,如果我们在Spring Boot中有一个Java类,并且在类级别上有一个Logger对象。现在,在此类中,我们有异步调用。现在,当这个异步呼叫开始时。它会在其堆栈中创建所有需要变量的单独副本吗?还是将使用主线程中类级别创建的相同对象?

例如,想象我们在类级别上有一些Logger对象,我们正在使用这些对象来记录主线程。现在,如果我们在同一类中的某些方法中以某种方法访问它。此异步调用会使用主对象的同一logger对象,还是它将在其堆栈中具有自己的Logger对象的新副本?

问题2)第二个问题之后是第一个问题的回答,如果异步调用将在父线程中初始化的对象的单独副本,那么当两个线程尝试同时访问相同对象时,为什么会出现异常因为两者都有同一对象的单独副本。

问题3),如果singleton的任何bean的范围,它仍然会在异步调用中创建其对象的新副本吗?还是在主线程和异步调用之间共享相同的对象?

I want to clarify three confusions here.

Question 1) My first question is that if we have a Java class in spring boot and we have one logger object at class level. Now inside this class in some function we have async call. Now when this asynchronous call will start . will it creates separate copy of all needed variables, in its stack ? or it will use same objects created at class level in main thread ?

For example imagine that we have some logger object at class level, which we are using for logging in main thread. Now if we access it in our async thread call in some method in same class. Will this async call use same logger object of main object or it will have its own new copy of logger object in its stack ?

Question 2) second questions is followed by answer of first questions, if async call will have separate copy of objects initialized in parent thread, then why exception occurs when both threads try to access same object at same time, as both have separate copies of same object.

Question 3) and if scope of any bean is singleton, still new copy of its object will be created in async call ? or same object will be shared among both main thread and async call ?

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

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

发布评论

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

评论(1

冷清清 2025-02-19 09:47:33

异步调用调用一种方法,该方法中定义的所有局部变量都存在于方法调用的堆栈框架上。因此,这些是属于该方法调用的副本,并且仅通过执行异步方法的线程才能访问它们。

实例变量和类变量(如记录器)与同步呼叫相同,没有复制它们。如果您的异步方法引用了一个存储库,而另一种方法引用了同一存储库,则两个都在调用同一对象。

其他问题似乎是基于对第一个问题的误解。

您正在调用该方法的弹簧组件不应具有对话状态,实例成员应为其他弹簧组件。登录器设计为在线程之间共享。

The async call invokes a method, all local variables defined in that method exist on the stack frame of the method call. So those are copies that belong to that method invocation and they are accessed only by the thread executing the async method.

Instance variables and class variables, like the logger, are the same as for synchronous calls, they are not copied. If your async method references a repository, and another method references that same repository, both are calling the same object.

The other questions seem based on a misunderstanding of this first issue.

A spring component that you're calling the method on should not have conversational state, the instance members should be other spring components. Loggers are designed to be shared between threads.

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