Sharing ApplicationContext with Executors

Let me clear agenda first:

  1. I have 1000 request data.
  2. I will read all the 1000 request and i will submit the 1000 request to executors.
  3. Each task will hit the soap webservice and get the response.

Question:

  1. I have shared application context which will be same for all the threads.
  2. In the bean.xml file I have protoype bean which I want to use to make the soap request.
  3. If I use the shared application context and get the proptype bean then will it be cause any synchrinizattion issue on shared app context variable.

Below is the sample code:

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();



    }
}

It depends on what your Runnables do. If they’re stateless beans and do not share/modify same variables/references with the other Runnables, then generally you’re safe. getBean() will return a new instance if the bean scope is prototype.

Be careful with the pool size, make sure you set a reasonable pool size(See this). Also, make sure your worker Threads which make the web service request have proper timeouts set.