Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Automata-Based Programming in Spring

DZone's Guide to

Automata-Based Programming in Spring

While it's an older concept, automata-based programming has plenty of modern use cases. See what they are and how Spring Statemachine helps.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Using FSM (finite state machines) for modeling in software development is not a new concept. Automata-based techniques have been widely used in domains like formal language analyses. However, applications of finite state machines were further investigated and applied as a general purpose program development methodology.

The programming paradigm in which the program, or part of it, is thought of as a model of a finite state machine (FSM) is called Automata-Based Programming.

The term Automata-Based Programming was introduced in 1997 on a multi-agent systems conference (held near St. Petersburg) by N. Polikarpova, one of the authors of the book Automata-Based Programming (called Автоматное программирование in Russian). The English term was mentioned a bit later in an English article published by Shalyto. It was named Automata Programming or a Switch technology. This technology is based on the projecting of systems or parts of them as sets of connected finite automata.

As you most likely know, automata theory is a branch of computer science that established its roots during the 20th Century. As a matter of fact, the first people to consider the concept of a finite-state machine included biologists, psychologists, mathematicians, engineers, and some of the first computer scientists. They all shared a common interest: to model the human thought process, whether in the brain or in a computer.

Warren McCulloch and Walter Pitts, a neurophysiologist and a logician, were the first to present a description of finite automata in 1943. Their paper, titled "A Logical Calculus Immanent in Nervous Activity," can be regarded as the inception of two fields of research.

One is the theory of finite-state machines as a model of computation. The other one is the field of artificial neural networks. Later, two computer scientists, G.H. Mealy and E.F. Moore, generalized the theory to much more powerful machines in separate papers, published in 1955-56. The finite-state machines, the Mealy machine and the Moore machine, are named in recognition of their work. In 1967, Minsky published his book Computation: Finite and Infinite Machines. This book was really not an AI book, but rather a book on the power of various types of abstract machines.

Nowadays, there are ready-to-use frameworks useful for the definition of state machine instances, and this article is dedicated to Spring. Spring Statemachine is a framework for application developers to use state machine concepts with Spring applications. As the Spring Statemachine documentation states:

Spring Statemachine project is a good candidate to use state machine if:

  • Application or part of its structure can be represented as states.
  • You want to split complex logic into smaller manageable tasks.
  • Application is already suffering concurrency issues with i.e. something happening asynchronously.

You are already trying to implement a state machine if:

  • Use of boolean flags or enums to model situations.
  • Having variables which only have meaning for some part of your application lifecycle.
  • Looping through if/else structure and checking if particular flag or enum is set and then making further exceptions what to do when certain combination of your flags and enums exists or doesn’t exist together.

The project ships with quite a lot of examples showing various features solving different problems with specific levels of complexity. Let's take a look at the simplest one:

@Configuration
public class Application {

    @Configuration
    @EnableStateMachine
    static class StateMachineConfig
    extends EnumStateMachineConfigurerAdapter < States, Events > {

        @Override
        public void configure(StateMachineStateConfigurer < States, Events > states)
        throws Exception {
            states
                .withStates()
                .initial(States.LOCKED)
                .states(EnumSet.allOf(States.class));
        }

        @Override
        public void configure(StateMachineTransitionConfigurer < States, Events > transitions)
        throws Exception {
            transitions
                .withExternal()
                .source(States.LOCKED)
                .target(States.UNLOCKED)
                .event(Events.COIN)
                .and()
                .withExternal()
                .source(States.UNLOCKED)
                .target(States.LOCKED)
                .event(Events.PUSH);
        }

    }

    public enum States {
        LOCKED,
        UNLOCKED
    }
    public enum Events {
        COIN,
        PUSH
    }

    public static void main(String[] args) throws Exception {
        Bootstrap.main(args);
    }
}


The example represents the classical Turnstile use case. It shows the basic futures of the framework. The framework is built around the Builder pattern and provides a Fluent API. The language used to define the state machine is clear and simplistic. Based on that, the developer can extend the basic constructs with additional functionalities provided by the framework:

  • Hierarchical state machine structure to ease complex state configuration;

  • State machine regions to provide even more complex state configurations;

  • Usage of triggers, transitions, guards, and actions;

  • Distributed state machine based on a Zookeeper;

  • State machine event listeners;

  • UML Eclipse Papyrus modeling;

  • Store machine config in a persistent storage;

  • Spring IOC integration to associate beans with a state machine.

Spring Statemachine might be your preferred solution if you face similar use cases and want to build a stable, structured, and extensible application.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
finite state machine ,spring ,java ,automata-based programming ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}