Home > Net >  Java - State pattern: Using threads within the states
Java - State pattern: Using threads within the states

Time:06-29

I want to coordinate serial requests coming from a Java Swing GUI using the state pattern. When a state method was called, the serial communication shall start and in parrallel the GUI should not be frozen during this time.

I have one GUI Thread. In this thread I'm invkoing methods of a state machine which also lives in the GUI Thread. In some cases after a state machine method has been invoked, data from a serial port shall be fetched (longer task). This fetching is been done in an otherThread. On some state changes the otherThread can be interrupted and otherThread should stop immediately (I'm using otherThread.interrupt()). To know when otherThread actually has returned, I use otherThread.join() to wait for otherThread in the GUI Thread.

Without using join() I always run into exceptions after a state change where I communicate via serial port in another otherThread.

The inconvinience of this approach is ofc. that the GUI thread is blocked/frozen as long as otherThread needs to finish its task.

I was thinking about calling the state machine method in a third thread. But I don't like this idea bcs.:

  • I don't have a lot experience with multi threading in Java (I assume labeling the methods of the state machine as synchronized could work to ensure thread safetiness).
  • Overhead due to thread and runnable creation for each invocation of a state machine method.

So my question is: What is a good way to make the GUI not frozen while waiting for otherThread?

CodePudding user response:

All the stuff about "states", "state machines", and "state pattern" is red herring. (Meaning: it is completely irrelevant.) The question is simply how to avoid block-waiting for Thread.join() from the gui thread.

Your "otherThread" should be aware of the fact that it was interrupted and exit gracefully. (Look for more information on thread interruption in Java to see how to accomplish this correctly.)

Right before exiting, the "otherThread" should post a message back to your "gui thread" to let it know that it is exiting.

Posting a message back to the "gui thread" in Swing is done with SwingUtilities.invokeLater(), and the "message" is not exactly a message, it is a function that you pass to invokeLater() and it gets executed within the "gui thread".

Then, the "gui thread" can then either ignore the thread, or join with it, knowing that this Thread.join() will complete very quickly because thread termination is either imminent, or has already happened.

  • Related