Finite state machine implemented in Java language
SimpleFSM fsm = new SimpleFSM() { (1)
@Override
public void onExit(Exception ex) { (2)
System.out.println("THE END with error=" + ex);
System.out.println("vals = " + Arrays.toString( (int[]) this.get("val")) );
}
};
int secs[] = new int[]{3, 0};
Node n2 = fsm.addState("T1", () -> { (3)
System.out.printf("First Node pausa=%d secs\n", secs[0]);
TimeUnit.SECONDS.sleep(secs[0]--);
}).setTimeout(2000) (4)
.setRetries(5); (4)
fsm.addState(() -> { (3)
System.out.println("no name");
if (val[1]++ == 0) throw new Exception("I don´t like zeros!");
}).setNextOnError("T1"); (5)
fsm.addState("T3", () -> {
System.out.println("Third Node");
secs[0] = 7;
}).setNext("T1"); (4)
//Redirect the log output to the sys out
//fsm.setLogStream(System.out); (6)
fsm.print(); (7)
fsm.start(); (8)
//fsm.startInSameThread(); (9)
// System.out.println("Must stop now!!");
// fsm.mustStop();
-
Implement an object of the class SimpleFSM
-
If you want you can override the onExit method to be signalized when the FSM finishes
-
Add a state, you can pass a name or ommit it.
-
You can define the Timeout, number of retries and the next state to be executed on success
-
… or the next one to go in when something goes wrong
-
Define your log output
-
Print the nodes
-
Start the state machine on a separate thread
-
Start the state machine on the current thread
The SimpleFSM is capable of store store variables, so like a hashmap, you are able to simply call: fsm.save(key, some_object ) and after the execution the value will be able to be got using fsm.get(key).
final SimpleFSM fsm = new SimpleFSM() { (3)
@Override
public void onExit(Exception ex) {
System.out.println("THE END with error=" + ex);
System.out.println("vals = " + Arrays.toString( (int[]) this.get("val")) ); (2)
}
};
int val[] = new int[]{5, 0};
Node n2 = fsm.addState("T1", () -> {
System.out.printf("First Node pausa=%d secs\n", val[0]);
fsm.save("val", val ); (1)
TimeUnit.SECONDS.sleep(val[0]--);
}).setTimeout(2000)
.setRetries(5);
-
Save the data using the fsm object (3)
-
Inside onExit we are in the fsm instance, so this points to the object itself