View Javadoc

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