title: spring state machine in multi threaded environment
body: <p>We have just started using spring state machine. Have a couple of questions:</p>
  
  <ul>
  <li>Is the state context only once per state machine? </li>
  <li>Do the events passed to the state machine run in a blocking way? Any way to make them run in parallel, like, providing a new state machine everytime an event is triggered?</li>
  </ul>
  
  <p>Here is my code:</p>
  
  <p><em>Configuring the states and transitions:</em></p>
  
  <pre><code>@Override
  public void configure(
          StateMachineTransitionConfigurer&lt;WorkFlowStates, WorkFlowEvent&gt; transitions)
                  throws Exception {
      transitions
      .withExternal()
      .source(WorkFlowStates.ready)
      .target(WorkFlowStates.l1Creation)
      .event(WorkFlowEvent.createWorkItem)
      .action(workFlowCreator.createL1())
  </code></pre>
  
  <p><em>Providing actions during state transitions:</em></p>
  
  <pre><code>public Action&lt;WorkFlowStates, WorkFlowEvent&gt; createL3() {
      return new Action&lt;WorkFlowStates, WorkFlowEvent&gt;() {
  
          public void execute(StateContext&lt;WorkFlowStates, WorkFlowEvent&gt; context) {
              System.out.println("l3 creation in action");
              Map&lt;Object, Object&gt; variables = context.getExtendedState().getVariables();
              Integer counter = (Integer)variables.get("counter");
              if(counter == null) counter = 1;
              else counter = counter+1;
              variables.put("counter", counter);
              System.out.println("Counter is "+counter);
              try {
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              variables.put(Level.l3, WorkItemFactory.createFailureL1L2L3WorkItem());
              variables.put("level", Level.l3);
              System.out.println("l3 created");
          }
      };
  }
  </code></pre>
  
  <p>Task executor:</p>
  
  <pre><code>public void configure(StateMachineConfigurationConfigurer&lt;WorkFlowStates, 
  WorkFlowEvent&gt;config)
                  throws Exception {
      config
      .withConfiguration()
      .autoStartup(true)
      .taskExecutor(taskExecutor())
      .listener(new WorkFlowStateMachineListener()); 
  }
  
  @Bean(name = StateMachineSystemConstants.TASK_EXECUTOR_BEAN_NAME)
  public TaskExecutor taskExecutor() {
      ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
      taskExecutor.afterPropertiesSet();
      taskExecutor.setCorePoolSize(5);
      return taskExecutor;
  }
  </code></pre>
  
  <p><em>And events passed to the state machine:</em></p>
  
  <pre><code>StateMachine&lt;WorkFlowStates, WorkFlowEvent&gt; stateMachine = 
      context.getBean(StateMachine.class);
  
      stateMachine.sendEvent(WorkFlowEvent.createWorkItem);
      stateMachine.sendEvent(WorkFlowEvent.createWorkItem);
  </code></pre>