loolooyyyy
Posts: 2
Joined: Fri Dec 11, 2015 11:28 am

Is PI4J's event listener thread-safe?

Fri Dec 11, 2015 11:39 am

Hi.

I'm implementing a SerialDataEventListener from PI4J and need to receive packets of length 16 bytes from serial port. My listener waits until at least 16 bytes have arrived and sends those bytes to some packet processor.

But I'm wondering: what if PI4J calls my listener twice for two events of -let's say- 14 and 2 bytes? does PI4J wait (blocks) until I process the first 10 bytes?
Even if I use a SynchronizedDeque, it doesn't help as it is matter of which listener callback (for 2 bytes or for 14 bytes) will call the deque.add()'s method first.

If PI4J does not wait/block, I see no way of synchronizing with 100% certainty about order bytes while waiting for more than 1 byte.

User avatar
savageautomate
Posts: 225
Joined: Thu Aug 16, 2012 3:20 pm
Location: USA
Contact: Website

Re: Is PI4J's event listener thread-safe?

Fri Dec 11, 2015 5:50 pm

Yes, Pi4J does block on the callback event method invocation. With that said, you probably don't want any long running/blocking operations taking place directly in the event handler. Its fine for short tasks, but just don't block the event callback for long periods of time.

If you are not already, I would suggest using the latest builds of Pi4J 1.1-SNAPSHOT to get the new serial interfaces and implementation. There has been much improvement to the serial implementation in v1.1.
https://github.com/Pi4J/pi4j/blob/devel ... ample.java

Here is where the actual native threading is implemented for the serial events:
https://github.com/Pi4J/pi4j/blob/devel ... nterrupt.c

Thanks, Robert
Robert Savage | Follow me @savageautomate
http://www.pi4j.com | http://www.pislices.com
http://www.savagehomeautomation.com

loolooyyyy
Posts: 2
Joined: Fri Dec 11, 2015 11:28 am

Re: Is PI4J's event listener thread-safe?

Sun Dec 13, 2015 9:33 am

That ended our two weeks hassle and trouble, a thousand thanks Robert.

User avatar
savageautomate
Posts: 225
Joined: Thu Aug 16, 2012 3:20 pm
Location: USA
Contact: Website

Re: Is PI4J's event listener thread-safe?

Sun Dec 13, 2015 11:30 pm

Glad I could help :-)

Thanks, Robert
Robert Savage | Follow me @savageautomate
http://www.pi4j.com | http://www.pislices.com
http://www.savagehomeautomation.com

Return to “Java”