Order lifecycle. Payment authorization. Device provisioning. KYC review. Every one of these is a finite state machine wearing a business-domain costume, and every Java team eventually writes one — usually three times, badly, before reaching for a library. Then they discover the uncomfortable truth of the 2026 JVM ecosystem: the three best-known Java state machine libraries have 1,660, 2,257 and 941 GitHub stars, and two of them haven’t seen a commit since 2024 and 2023 respectively.

That doesn’t mean you shouldn’t use one. It means the decision is no longer “which library has the nicest DSL” — it’s “which dependency am I willing to own for the next five years, and what’s my exit plan.” Here’s the honest comparison, with the Maven coordinates and transition code you’ll actually type.

TL;DR — the verdict before the details

  • Spring Statemachine 4.0 if you’re on Spring Boot 3 and want persistence, a StateMachineService, and integration with Spring’s transaction and messaging machinery. It’s the only one of the three still actively maintained. Recommended default.
  • Stateless4j 2.6.0 if you want a small, dependency-free library that models a simple FSM in ~20 lines and you’re comfortable vendoring it. It’s frozen, but its API surface is tiny enough that “frozen” is survivable.
  • Squirrel 0.3.10 only for existing codebases. Great fluent API and annotation-driven definitions, highest star count — and no commits since June 2024. New projects should not adopt it.
  • If none of them fit: model the machine explicitly in your domain layer (an enum plus a transition table is often 60 lines), or push orchestration to a durable engine like the ones in our self-hosted saga orchestrator comparison.

My blunt take: Spring Statemachine for anything that must survive a restart; hand-rolled transition tables for anything that doesn’t.

Comparison table (live data, December 2026)

Spring StatemachineSquirrelStateless4jHand-rolled enum FSM
GitHub stars1,6602,257941n/a
Last commit2026-07-052024-06-042023-06-17n/a
MaintenanceActive (4.0.0)DormantDormantYou
Maven coordinateorg.springframework.statemachine:spring-statemachine-coreorg.squirrelframework:squirrel-foundationcom.github.stateless4j:stateless4j—
Current version4.0.00.3.102.6.0—
Spring dependencyRequiredNoneNoneNone
PersistenceBuilt in (StateMachinePersister, JPA/Redis)ManualNoneManual
DSL styleFluent configurer + annotationsFluent builder + annotationsFluent configure()switch / map
Hierarchical statesYesYesNoNo
Guards / actionsYesYesYes (Guard, entry/exit)Yes
Java baseline17 (Spring Framework 6)8+8+Any
Best fitSpring services, long-running processesLegacy apps already using itSimple in-memory FSMDomain logic with few states

Decision matrix — pick in 10 seconds

Your situationUseWhy
Spring Boot 3 service, state must survive restartsSpring Statemachine 4.0Persister + StateMachineService already built
Simple in-memory order flow, no SpringStateless4j20 lines, no transitive dependencies
Existing codebase already on SquirrelSquirrel (pinned)Don’t rewrite to fix a maintenance problem you can bound
Complex nested states (substates, orthogonal regions)Spring StatemachineOnly one with real hierarchical state support
State lives in your database and you want it in one columnHand-rolled + enumA library adds indirection, not safety
Long-running workflow with timers, retries, compensationTemporal / CamundaFinite state machines don’t schedule
Kotlin or Go serviceSee our Go FSM comparisonIdiomatic libraries differ by language

Spring Statemachine 4.0 — the maintained option

Spring Statemachine (SSM) is the heavyweight: hierarchical states, regions, guards, actions, a StateMachineService, and persistence adapters. Version 4.0.0 targets Spring Framework 6 and Java 17, which means it slots into a Boot 3 application without version gymnastics.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<dependency>
    <groupId>org.springframework.statemachine</groupId>
    <artifactId>spring-statemachine-core</artifactId>
    <version>4.0.0</version>
</dependency>
<!-- optional: Boot auto-configuration and persistence -->
<dependency>
    <groupId>org.springframework.statemachine</groupId>
    <artifactId>spring-statemachine-autoconfigure</artifactId>
    <version>4.0.0</version>
</dependency>

Configuration is declarative and type-safe over your enums:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Configuration
@EnableStateMachine
public class OrderStateConfig extends StateMachineConfigurerAdapter<OrderState, OrderEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {
        states.withStates()
              .initial(OrderState.NEW)
              .states(EnumSet.allOf(OrderState.class))
              .end(OrderState.COMPLETED)
              .end(OrderState.CANCELLED);
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) throws Exception {
        transitions
            .withExternal().source(OrderState.NEW).target(OrderState.AUTHORIZED)
                .event(OrderEvent.AUTHORIZE).action(authorizeAction())
            .and()
            .withExternal().source(OrderState.AUTHORIZED).target(OrderState.SHIPPED)
                .event(OrderEvent.SHIP).guard(inventoryAvailable())
            .and()
            .withExternal().source(OrderState.NEW).target(OrderState.CANCELLED)
                .event(OrderEvent.CANCEL);
    }

    @Bean
    public Action<OrderState, OrderEvent> authorizeAction() {
        return ctx -> ctx.getExtendedState().getVariables().put("authAt", Instant.now());
    }

    @Bean
    public Guard<OrderState, OrderEvent> inventoryAvailable() {
        return ctx -> inventoryService.hasStock(ctx.getExtendedState().get("sku", String.class));
    }
}

The part that justifies the dependency is persistence. A StateMachinePersister writes machine state into your database, so an order that sat in AUTHORIZED when the pod restarted resumes there:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@Autowired
private StateMachineService<OrderState, OrderEvent> stateMachineService;

@Autowired
private StateMachinePersister<OrderState, OrderEvent, String> persister;

public void ship(String orderId) throws Exception {
    StateMachine<OrderState, OrderEvent> machine =
        stateMachineService.acquireStateMachine(orderId);
    machine.sendEvent(OrderEvent.SHIP);
    persister.persist(machine, orderId);
    stateMachineService.releaseStateMachine(orderId);
}

Spring Boot 3 auto-configuration supplies a JpaStateMachineRepository (or Redis) when the right starter is on the classpath, so you get durable state without writing a repository yourself.

SSM’s downsides are real and worth saying plainly: it’s a large surface area, its documentation lags the code in places, error messages during misconfiguration are unfriendly (StateMachineException with a stack trace that points at the configurer, not the bug), and the fluent and() chains become hard to read past ~15 transitions. Large machines belong in a diagram tool — which is exactly what the official docs use:

Spring Statemachine modeling with Eclipse Papyrus

If your machine has more than about 20 states, generate the configurer from a model rather than hand-writing it.

Squirrel has the most stars of the three (2,257) and the nicest fluent API. It also has no commits since June 2024 and its last Maven release is 0.3.10. That combination — popular, polished, dormant — is the classic trap in dependency selection.

1
2
3
4
5
<dependency>
    <groupId>org.squirrelframework</groupId>
    <artifactId>squirrel-foundation</artifactId>
    <version>0.3.10</version>
</dependency>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
StateMachineBuilder<OrderState, OrderEvent, OrderContext> builder =
    StateMachineBuilderFactory.create(
        OrderStateMachine.class, OrderState.class, OrderEvent.class, OrderContext.class);

builder.externalTransition()
       .from(OrderState.NEW).to(OrderState.AUTHORIZED)
       .on(OrderEvent.AUTHORIZE)
       .when(ctx -> ctx.getOrder().hasPaymentMethod())
       .perform((from, to, event, ctx) -> ctx.setAuthorizedAt(Instant.now()));

StateMachine<OrderState, OrderEvent, OrderContext> machine =
    builder.newStateMachine(OrderState.NEW);
machine.start();
machine.fire(OrderEvent.AUTHORIZE, context);

Or annotation-driven, which is Squirrel’s real differentiator:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@States({OrderState.NEW, OrderState.AUTHORIZED, OrderState.SHIPPED})
@Transitions({
    @Transit(from = OrderState.NEW, to = OrderState.AUTHORIZED, on = OrderEvent.AUTHORIZE),
    @Transit(from = OrderState.AUTHORIZED, to = OrderState.SHIPPED, on = OrderEvent.SHIP)
})
public class OrderStateMachine extends AbstractStateMachine<OrderState, OrderEvent, OrderContext> {
    @Override
    protected void afterTransitionDeclined(OrderState from, OrderEvent event, OrderContext ctx) {
        log.warn("rejected {} from {}", event, from);
    }
}

The API is good. The problem is everything around it: no releases in years, no fixes for newer JDK bytecode edge cases, and no security patches. If you’re already on Squirrel, pin the version, keep a fork branch, and treat the library as vendored source. Do not start anything new on it — and do not be swayed by the star count, which mostly accumulated between 2015 and 2019.

Stateless4j 2.6.0 — small, frozen, still useful

Stateless4j is a port of the .NET Stateless library and does one thing: a lightweight FSM with entry/exit actions, guards, and a readable configuration API. Its README example is the whole library:

1
2
3
4
5
<dependency>
    <groupId>com.github.stateless4j</groupId>
    <artifactId>stateless4j</artifactId>
    <version>2.6.0</version>
</dependency>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
StateMachineConfig<State, Trigger> phoneCallConfig = new StateMachineConfig<>();

phoneCallConfig.configure(State.OffHook)
        .permit(Trigger.CallDialed, State.Ringing);

phoneCallConfig.configure(State.Ringing)
        .permit(Trigger.HungUp, State.OffHook)
        .permit(Trigger.CallConnected, State.Connected);

phoneCallConfig.configure(State.Connected)
        .onEntry(this::startCallTimer)
        .onExit(this::stopCallTimer)
        .permit(Trigger.LeftMessage, State.OffHook)
        .permit(Trigger.HungUp, State.OffHook)
        .permit(Trigger.PlacedOnHold, State.OnHold);

StateMachine<State, Trigger> phoneCall =
        new StateMachine<>(State.OffHook, phoneCallConfig);

phoneCall.fire(Trigger.CallDialed);
// State.Ringing

No Spring, no persistence, no hierarchy, no dependencies. Last commit June 2023 and 941 stars. For a device handshake, a connection state machine, or a UI flow with six states, it’s a perfectly reasonable 40 KB of code to own — the API is stable enough that “frozen” means “done,” not “broken.” Just don’t confuse it with a workflow engine: no timers, no retries, no durable state, no distributed coordination.

What to do instead (the honest section)

Three legitimate alternatives to adopting any of the above:

1. A transition table in your domain layer. For 5–10 states, an EnumMap<State, Map<Event, State>> plus guard predicates is more readable than a configurer DSL and has zero dependency risk:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private static final Map<OrderState, Map<OrderEvent, OrderState>> ALLOWED = Map.of(
    OrderState.NEW, Map.of(OrderEvent.AUTHORIZE, OrderState.AUTHORIZED,
                           OrderEvent.CANCEL, OrderState.CANCELLED),
    OrderState.AUTHORIZED, Map.of(OrderEvent.SHIP, OrderState.SHIPPED)
);

public OrderState apply(OrderState current, OrderEvent event) {
    return ALLOWED.getOrDefault(current, Map.of())
                  .entrySet().stream()
                  .filter(e -> e.getKey() == event)
                  .map(Map.Entry::getValue)
                  .findFirst()
                  .orElseThrow(() -> new IllegalStateException(current + " rejects " + event));
}

2. Durable orchestration. If your state machine involves waiting for humans, scheduling retries, or compensating failed steps, you want a workflow engine, not an FSM library. See the saga orchestrator comparison linked above, or the BPMN engine comparison of Flowable, Activiti and Camunda.

3. A language-appropriate library. The JVM’s state machine ecosystem stagnated while the problem moved elsewhere. Our state machine library comparison across JavaScript and C++ and the C++ trio of Boost.SML, TinyFSM and HFSM2 show what active maintenance looks like in 2026.

Pitfalls that bite in production

State machine + database transaction is a two-phase problem. SSM’s StateMachinePersister writes state after the transition fires, inside the same JVM call. If your business write and the state persist aren’t in one transaction, a crash between them leaves an order shipped but marked AUTHORIZED. Wrap both in @Transactional and persist inside it.

Concurrent events on the same machine instance corrupt state. StateMachineService.acquireStateMachine(id) is your lock — two threads calling sendEvent on the same acquired machine produce interleaved transitions and a state you can’t reproduce. Always release in a finally block; a leaked acquisition is a permanent deadlock for that entity.

Guards that call the network are a latency bomb. A guard querying inventory turns a state transition into a remote call with no timeout by default. Put the timeout in the guard itself, and prefer passing a pre-fetched fact through ExtendedState over resolving inside the guard.

EnumSet.allOf(...) hides terminal states. Registering every enum value as a state means a typo in a transition target compiles fine. Declare .end(...) explicitly and write a test that asserts unreachable states are actually unreachable.

Squirrel’s annotation processor and newer JDKs drift. Annotation-driven machines on JDK 21+ can hit bytecode or reflective-access edge cases with no upstream fix coming. If you’re on Squirrel and planning a JDK upgrade, budget time to fork.

Don’t model money as a state. A state machine tracks where an entity is, not how much it’s worth. The most common design smell in order FSMs is stuffing payment amounts and retry counts into ExtendedState and then persisting them ad hoc — those belong in your entity table, not the machine’s variable map.

FAQ

Is Spring Statemachine still maintained in 2026?

Yes. Version 4.0.0 is the current release on Maven Central and the repository received commits in July 2026 — it is the only one of the three Java FSM libraries compared here with active maintenance. Its release cadence is slow compared to Spring Boot itself, so pin the version and test upgrades deliberately.

Should I use Squirrel for a new project?

No. Squirrel 0.3.10 is the last Maven release and the repository has had no commits since June 2024, despite 2,257 stars. Use it only in codebases that already depend on it, and keep a fork for JDK upgrade fixes.

What replaced Stateless4j?

Nothing directly — Stateless4j is feature-frozen rather than replaced. For JVM work, teams either move to Spring Statemachine (if they need persistence and hierarchy) or hand-roll an enum transition table. For Kotlin, coroutine-friendly alternatives exist in the Kotlin ecosystem.

Do I even need a state machine library?

If you have fewer than roughly ten states, no external events causing transitions, and no need to persist mid-flow state, a transition table with guards in your domain layer is clearer and safer than any library. Libraries earn their keep when you need hierarchical states, durable persistence, or distributed coordination.

How do I persist state machine state across restarts?

With Spring Statemachine, use StateMachinePersister with the JPA or Redis repository from spring-statemachine-autoconfigure, and persist inside the same transaction as your business write. With Stateless4j, you have no persistence layer — store the current state enum in your entity row and reconstruct the machine on load.

Can Spring Statemachine handle timers and scheduled transitions?

Yes, through StateMachineService plus a scheduled task that fires events, or by integrating with Spring’s TaskScheduler. For anything beyond simple timeouts — retries with backoff, human approval steps, compensation — use a durable workflow engine instead, because you’d otherwise be rebuilding one badly.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com