【问题标题】:Sharing ApplicationContext with Executors与 Executor 共享 ApplicationContext
【发布时间】:2017-08-01 08:13:40
【问题描述】:

让我先明确议程:

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

问题:

  1. 我已共享应用程序上下文,所有线程都相同。
  2. 在 bean.xml 文件中,我有原型 bean,我想用它来发出肥皂请求。
  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();



    }
}

【问题讨论】:

    标签: java spring soap executorservice


    【解决方案1】:

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

    注意池大小,确保设置合理的池大小(参见this)。另外,请确保发出 Web 服务请求的工作线程设置了适当的超时时间。

    【讨论】:

    • 在我的 Runnable 中,我将使用原型 bean 来访问 web 服务。我所有的任务都是从同一个应用程序上下文中获取原型 bean,所以我的同一个应用程序上下文会导致任何问题吗?请帮助代码将与我上面提到的相同
    • 不同线程从同一个Application Context获取worker bean是没有问题的。但是,如果您的工作 bean 共享/修改相同的变量/引用,那么就会出现问题。
    • 共享同一个变量是什么意思,我认为你的意思是通过同一个应用程序上下文共享单例bean?因此,如果它的原型 bean 由应用程序上下文提供服务,那么我没有任何问题
    • 你需要阅读线程安全tutorials.jenkov.com/java-concurrency/thread-safety.html。例如,假设您将全局计数器简单地保留为int 变量,并在处理每个请求(来自工作线程)后更新它,那么您的代码不是线程安全的 - 您有竞争条件,所以您需要一个适当的锁定或AtomicInteger 来更新这个计数器。
    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2014-10-08
    • 2010-12-10
    • 2012-12-11
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多