Working with blocked I/O calls

Some time ago, I happened to work with Lego Mindstorms. Rather than learn yet another programming notation for Mindstorms, I preferred to use LeJOS.

However, LeJOS was based on Java 1.2, which had blocked I/O calls. This means that an I/O write was not completed until a corresponding I/O read was executed at the receiver. Similarly, an I/O read was not executed till someone wrote to the buffer.

How is this different from unblocked I/O? In the latter scenario, we poll the buffer status like this:

while(true) {
  sbuf = inputStream.read(byteArr);
  if (sbuf != null) {
    //code to process byteArr
  }
  //other processing to be done
}

In case of blocked I/O, the program waits for inputStream.read to get executed, till a point that the input buffer actually contains some data. Of course, this makes the check sbuf != null worthless, but more important is the fact that the “Other processing” we’d like to do never gets done until the input buffer is populated. Why is this important? Because in most cases we want to process a lot more than a single data stream. For example, in my LeJOS program, I was handling inputs from touch sensors, a light sensor and an Infrared sensor.

(A bit about my LeJOS program: I was trying a basic car driving program which could understand walls with touch sensors, car driving in front using light sensor and vehicle coming head-on using infrared sensor.  Although my Infrared sensor could be accessed using the usual I/O calls, it meant blocking up all the processing till someone actually sent me a signal.)

The easy way out of blocked I/O is multi-threading. The parent class polls the buffer data held in the child class (where both classes are threads and run independently). If there is valid data, we read and respawn the child class. Else we continue (in an infinite loop) with other processing and return later to check data. The child class is the one which stays blocked, but that thread is dedicated to receiving data only. Our program execution continues safely.

For those interested, LeJOS code for basic car driving (with inputs from sensors) with Lego Mindstorms RCX kit is available here.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.