2017-08-01 51 views
0

讓我明確的議程第一:共享的ApplicationContext與執行人

  1. 我有1000個請求數據。
  2. 我會讀取所有1000個請求,並且我會將1000請求提交給執行者。
  3. 每個任務都會碰到soap web服務並獲得響應。

問:

  1. 我有共同的,這將是相同的所有線程應用程序上下文。
  2. 在bean.xml文件中,我有我想用來創建肥皂請求的protoype 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(); 



    } 
} 

回答

0

這取決於你Runnables做。如果他們是無狀態bean,並且不與其他Runnable s共享/修改相同的變量/引用,那麼通常你就是安全的。 getBean()將返回一個新的實例,如果豆的範圍是原型

請注意泳池的大小,確保設定合理的泳池大小(請參閱this)。此外,請確保您的工作線程提出Web服務請求已設置適當的超時。

+0

在我的Runnable中,我將使用prototype bean打擊web服務。 我所有的任務都是從相同的應用程序上下文獲取原型bean 所以我的同一個應用程序上下文會導致任何問題? 請幫忙 代碼和我上面提到的一樣 –

+0

通過不同的線程從相同的應用程序上下文獲取工作bean沒有問題。但是,如果你的工作者bean共享/修改相同的變量/引用,那麼就存在一個問題。 – isah

+0

你是什麼意思分享相同的變量,我想你的意思是共享同一個應用程序contex singleton bean? 所以如果它的原型bean服務於應用程序上下文,所以我沒有任何問題 –