2013-10-15 39 views
0

我有一個EJB被注入到我的一個類中。 EJB有一個方法來開始監視它所注入的類中的資源。監視器方法有一個while循環,如果其中一個變量被更新,那麼它需要被中斷。該代碼看起來是這樣的:有狀態EJB中的更新變量

public class MyObject() 
{ 
    @EJB 
    private MyEJB myEjb; 

    private Collection stuffToMonitor; 

    public MyObject() 
    { 
     //empty 
    } 

    public void doSomething() 
    { 
     // create collection of stuffToMonitor 

     myEjb.startMonitoring(stuffToMonitor); 

     // code that does something 

     if(conditionsAreMet) 
     { 
      myEjb.stopMonitoring(); 
     } 

     // more code 
    } 
} 

@Stateful 
public class MyEJB() 
{ 
    private volatile boolean monitoringStopped = false; 

    public MyEJB() 
    { 
     //empty 
    } 

    public void startMonitoring(Collection stuffToMonitor) 
    { 
     int completed = 0; 
     int total = stuffToMonitor.size(); 

     while(completed < total) 
     { 
      // using Futures, track completed stuff in collection 

      // log the value of this.monitoringStopped  
      if (this.monitoringStopped) 
      { 
       break; 
      } 
     } 
    } 

    public voide stopMonitoring() 
    { 
     this.monitoringStopped = true; 
     // log the value of this.monitoringStopped 
    } 
} 

在我的日誌,我可以看到this.monitoringStopped的值是true的stopMonitoring方法被調用後,但它總是記錄在while循環false

最初,MyEJB是無狀態的,它已被改爲有狀態,我也使變量volatile,但在while循環中沒有找到變化。

我錯過了什麼讓我的代碼得到更新的monitoringStopped變量的值?

回答

0

我想我試圖做的只是不可能與EJBS,但如果有人知道更好,我會很高興聽到他們。

相反,我找到了一種不同的方式。我添加了第三個類MyStatus,它包含MyObject將設置的狀態變量,而不是調用myEjb.stopMonitoring();。我將MyEJB設置爲無狀態bean,並在startMonitoring方法中將它傳遞給MyStatus對象。它會在while循環的每次迭代期間檢查狀態,並基於它進行分解。

更新代碼:

public class MyObject() 
{ 
    @EJB 
    private MyEJB myEjb; 

    @EJB 
    private MyStatus myStatus; 

    private Collection stuffToMonitor; 

    public MyObject() 
    { 
     //empty 
    } 

    public void doSomething() 
    { 
     // create collection of stuffToMonitor 

     myEjb.startMonitoring(stuffToMonitor); 

     // code that does something 

     if(conditionsAreMet) 
     { 
      myStatus.stopMonitor(); 
     } 

     // more code 
    } 
} 

@Stateless 
public class MyEJB() 
{ 
    private volatile boolean monitoringStopped = false; 

    public MyEJB() 
    { 
     //empty 
    } 

    public void startMonitoring(Collection stuffToMonitor, MyStatus myStatus) 
    { 
     int completed = 0; 
     int total = stuffToMonitor.size(); 

     while((completed < total) && myStatus.shouldMonitor()) 
     { 
      // using Futures, track completed stuff in collection 
     } 
    } 
} 

@Stateless 
public class MyStatus 
{ 
    private boolean shouldMonitor = true; 

    public void stopMonitor() 
    { 
     this.shouldMonitor = false; 
    } 

    public boolean shouldMonitor() 
    { 
     return this.shouldMonitor; 
    } 
}