Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Finite-state machines in Java

Finite-state machines in Java: A finite-state machine models state and event as enums or sealed types, with a transition function selecting the next state, often through an exhaustive switch expression.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

finite state machines

A finite-state machine models state and event as enums or sealed types, with a transition function selecting the next state, often through an exhaustive switch expression.

Represent state payloads as records in a sealed hierarchy and centralize transition(State, Event) so illegal transitions throw or return an explicit result.

Scattered boolean flags create impossible combinations, and mutating state without synchronization loses transitions under concurrency.

Guards must be checked before effects, side effects should follow an accepted transition, and AtomicReference.updateAndGet can make state replacement atomic.

The NEW→RUNNING→DONE transitions succeed, while START from DONE reaches the deterministic invalid:DONE+START failure.

Examples

public class Main {
    enum State { NEW, RUNNING, DONE }
    enum Event { START, COMPLETE }

    static State transition(State state, Event event) {
        return switch (state) {
            case NEW -> event == Event.START ? State.RUNNING : invalid(state, event);
            case RUNNING -> event == Event.COMPLETE ? State.DONE : invalid(state, event);
            case DONE -> invalid(state, event);
        };
    }

    static State invalid(State state, Event event) {
        throw new IllegalStateException("invalid:" + state + "+" + event);
    }

    public static void main(String[] args) {
        State state = transition(State.NEW, Event.START);
        System.out.println(state);
        state = transition(state, Event.COMPLETE);
        System.out.println(state);
        try {
            transition(state, Event.START);
        } catch (IllegalStateException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Result

RUNNING
DONE
invalid:DONE+START

The NEW→RUNNING→DONE transitions succeed, while START from DONE reaches the deterministic invalid:DONE+START failure.

Sources