RandomIO - laforge49/Asynchronous-Functional-Programming GitHub Wiki

RandomIO is a service for accessing a disk file. It uses two properties:

  • dbPathname - Provides the pathname of the file. (Required)
  • dbAccessMode - Specifies how the file is to be opened. (Defaults to "rw".)

The RandomIO service supports two types of messages:

case class ReadBytes(offset: Long, length: Int)
case class WriteBytes(offset: Long, bytes: Array[Byte])

RandomIO opens/closes its file when the actor it is aggregated with is opened/closed.

We will start by looking at a driver actor to exercise RandomIO.

case class DoIt()

class Driver extends Actor {
  bind(classOf[DoIt], doIt)

  def doIt(msg: AnyRef, rf: Any => Unit) {
    systemServices(WriteBytes(0, new Array[Byte](5000))) {
      rsp1 => {
        systemServices(ReadBytes(0, 5000)) {
          rsp2 => {
            rf(rsp2)
          }
        }
      }
    }
  }
}

The above code simply writes an array of bytes and then reads it back in. Here is the test code:

val dbName = "RandomIOTest.db"
val file = new java.io.File(dbName)
file.delete
val properties = new Properties
properties.put("dbPathname", dbName)
val systemServices = SystemServices(new RandomIOComponentFactory, properties = properties)
val driver = new Driver
driver.setMailbox(new ReactorMailbox)
driver.setSystemServices(systemServices)
val bytes = Future(driver, DoIt()).asInstanceOf[Array[Byte]]
bytes.length must be equalTo(5000)
systemServices.close

This code does the following:

  1. Delete the file, if present.
  2. Specifies a relative pathname for the file.
  3. Creates a SystemServices actor that includes the RandomIO service.
  4. Initializes and invokes the driver actor.
  5. Validates the length of the array that was read back in.

RandomIOTest

tutorial