非注入场会导致春季的竞争状况吗?

时间:2017-06-12 07:32:41

标签: java spring race-condition

我尝试在代码中使用State Pattern。但是我无法弄清楚这是否会导致Spring的竞争状态。 active stop restart具有不同的实施方式。将执行哪个实施取决于通过调用currentInt设置的setCurrentInt。如果是的话,我该如何处理这个问题。

@Component
public class StateService {

  //3 states
  @Autowired
  @Qualifier("notActivatedState")
  private ActiveState notActivatedState;
  @Autowired
  @Qualifier("stoppedState")
  private ActiveState stoppedState;
  @Autowired
  @Qualifier("inUseState")
  private ActiveState inUseState;
  //current state
  private Integer currentInt;



  //Interface which was delegated to perform an act. It is not @Autowired, could there be some problem when multiple requests set currentInt to different values ? 
  private ActiveState currentState;




  public void activate(BdCorp bdCorp) {
    currentState.activate(bdCorp);
  }

  public void stop(BdCorp bdCorp) {
    currentState.stop(bdCorp);
  }

  public void restart(BdCorp bdCorp) {
    currentState.restart(bdCorp);
  }


  public void setCurrentInt(Integer currentInt) {
    this.currentInt = currentInt;
    if (currentInt == 1) {
      this.currentState = notActivatedState;
    }
    if (currentInt == 2) {
      this.currentState = inUseState;
    }
    if (currentInt == 3) {
      this.currentState = stoppedState;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

当在赋值currentState之间更改currentIn时,它可能会出现并发问题。

而是定义,例如对于currentInt ThreadLocal并为当前状态而不是属性引入getter。

private ThreadLocal<Integer> currentIntStorage = new ThreadLocal<>();

private ActiveState getCurrentState() {
    Integer currentInt = myThreadLocal.get();
    if (currentInt == 1) {
      return notActivatedState;
    }
    else if (currentInt == 2) {
      return inUseState;
    }
    else if (currentInt == 3) {
      return stoppedState;
    }

    return null;
}

并使用它

public void activate(BdCorp bdCorp) {
  getCurrentState().activate(bdCorp);
}