View Javadoc
1   package com.atlassian.plugin.osgi.factory;
2   
3   public class ConcurrentStateEngine {
4       private final Object[] states;
5       private volatile int index = 0;
6   
7       public ConcurrentStateEngine(Object... states) {
8           this.states = states;
9       }
10  
11      public void tryNextState(Object expected, Object next) {
12          System.out.println("trying to move from " + expected + " to " + next + " but in " + states[index]);
13          int old = indexOf(expected);
14          int tries = 100;
15          while (old != index && tries-- > 0) {
16              try {
17                  Thread.sleep(100);
18              } catch (InterruptedException e) {
19                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
20              }
21          }
22          if (tries <= 0) {
23              throw new IllegalStateException("Timeout waiting for state");
24          }
25          state(next);
26      }
27  
28      public void state(Object next) {
29          index = indexOf(next);
30          System.out.println("Moved to state " + next + " (" + index + ")");
31      }
32  
33      private int indexOf(Object state) {
34          for (int x = 0; x < states.length; x++) {
35              if (states[x].equals(state)) {
36                  return x;
37              }
38          }
39          throw new IllegalStateException("Cannot find state " + state);
40      }
41  }