gpt4 book ai didi

java - 与执行者共享ApplicationContext

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:18 25 4
gpt4 key购买 nike

让我先明确议程:

  1. 我有 1000 个请求数据。
  2. 我将阅读所有 1000 个请求,并将这 1000 个请求提交给执行者。
  3. 每个任务都会访问 SOAP Web 服务并获取响应。

问题:

  1. 我共享了所有线程都相同的应用程序上下文。
  2. 在 bean.xml 文件中,我有原型(prototype) bean,我想用它来发出 SOAP 请求。
  3. 如果我使用共享应用程序上下文并获取 proptype bean,那么是否会导致共享应用程序上下文变量出现任何同步问题。

下面是示例代码:

import java.io.ObjectInputStream.GetField;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class AppContext
{
ApplicationContext sharedContext = new ClassPathXmlApplicationContext("Beans.xml");

public static ApplicationContext getAppContext()
{
if(sharedContext!=null)
return sharedContext; //will this cause any isseu while accessing by multiple threads
}

}

public class Testing {





public static void main(String args[])
{

//here I tried to submit the task using ExecutorService and want to use the same application context
//can I pass the prototypeBean in all the task with out synchronization issue?
//because My appcontext is static so will it cause any issue while accessing my multiple threads

ExecutorService service=Executors.newFixedThreadPool(10);
service.submit(new LoopTaskA(AppContext.getAppContext().getBean("myProtoTypeBean")));
service.submit(new LoopTaskA(AppContext.getAppContext().getBean("myProtoTypeBean")));
service.submit(new LoopTaskA(AppContext.getAppContext().getBean("myProtoTypeBean")));
service.submit(new LoopTaskA(AppContext.getAppContext().getBean("myProtoTypeBean")));
service.shutdown();



}
}

最佳答案

这取决于您的 Runnables 的用途。如果它们是无状态 bean 并且不与其他 Runnable 共享/修改相同的变量/引用,那么通常是安全的。如果 bean 范围是原型(prototype),getBean() 将返回一个新实例。

小心池大小,确保设置合理的池大小(请参阅 this )。另外,请确保发出 Web 服务请求的工作线程设置了正确的超时。

关于java - 与执行者共享ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45432422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com