2013-10-15 40 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; 
    } 
}