Using a thread pool for pin state notifications can reorder events
See original GitHub issuepi4j uses an internal thread pool to deliver PIN state events. Problem with this approach is that if your software is relying on the latest GpioPinDigitalStateChangeEvent.getState(), then, because the order of events in the thread pool is not guaranteed, your listener can end up having the wrong final event value, if the rate of event change is rapid enough.
Consider this PIN state change sequence:
1 LOW 2 HIGH 3 LOW
The final state is low, but if it so happens that the thread that delivers event (3) takes longer than the time difference between events (2) and (3), and the thread that delivers event (2) is faster, then the listener will see the events in this order:
1 LOW 3 LOW 2 HIGH
So the listener now erroneously thinks that the pin is in high state.
The workaround is to ignore the event value and always query the pin state in the event listener.
I think the idea of using a thread pool for pin state notifications, as opposed to a single thread, is not a good idea.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:13 (11 by maintainers)

Top Related StackOverflow Question
@ylexus ,
I think you will like the patterns we have in place for Pi4J V2. No static singletons. A Pi4J Context object is created (via builder pattern) and can be customized by the user for its runtime. All Pi4J references, lifecycles, threads, etc are all managed inside the context.
Here is an example/demo project: https://github.com/Pi4J/pi4j-demo-telegraph/blob/master/src/main/java/com/pi4j/demo/telegraph/Telegraph.java
This demo code also shows that I/O instances are created using builders. Lots of good stuff on the way …
@savageautomate I think we should change it for the 1.4 release as it has bad side affects. I will create a patch asap.