hekailiang / squirrel

squirrel-foundation is a State Machine library, which provided a lightweight, easy use, type safe and programmable state machine implementation for Java.
http://hekailiang.github.io/squirrel/
Other
2.19k stars 540 forks source link

Race condition upon the instantiation of declarative state machines #140

Open mr-khabib opened 1 year ago

mr-khabib commented 1 year ago

Periodically I'm getting ConcurrentModificationException/IllegalStateException while using Declarative fsm's.

I was able to partially reproduce with this UT:

@Test
    public void testRaceForUntypedStateMachine() {
        final CountDownLatch eventCondition = new CountDownLatch(5);
        StateMachineBuilder<DeclarativeStateMachine, TestState, TestEvent, Integer> bmyBuilder =
                StateMachineBuilderFactory.<DeclarativeStateMachine, TestState, TestEvent, Integer>
                        create(DeclarativeStateMachineImpl.class, TestState.class,
                        TestEvent.class, Integer.class, DeclarativeStateMachine.class);
        Thread thr1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    DeclarativeStateMachine fsm1 = bmyBuilder.newStateMachine(TestState.A, monitor);
                    fsm1.fire(TestEvent.InternalA, null);
                }
            }
        }, "Test-Thread-1");

        Thread thr2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    DeclarativeStateMachine fsm2 = bmyBuilder.newStateMachine(TestState.A, monitor);
                    fsm2.fire(TestEvent.InternalA, null);
                }

            }
        }, "Test-Thread-2");

        try {
            thr1.start();
            thr2.start();
            eventCondition.await(2, TimeUnit.SECONDS);
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            fail();
        }
    }

Issue reproduce in unpredictable manner - some time every run of this test, some time it needed to be run 10 times to get this state