Skip to content

Instantly share code, notes, and snippets.

@fwbrasil
Created April 6, 2012 20:01
Show Gist options
  • Save fwbrasil/2322553 to your computer and use it in GitHub Desktop.
Save fwbrasil/2322553 to your computer and use it in GitHub Desktop.
PrevaylerJr in Scala
import java.io._
class PrevaylerJr[T <: Serializable](initialState: T, pStorageFile: File) {
private val storageFile = new File(pStorageFile.getAbsolutePath + ".tmp")
private val system = {
val fileToRead = if (pStorageFile.exists) pStorageFile else storageFile
if (fileToRead.exists) {
val input = new ObjectInputStream(new FileInputStream(fileToRead))
/* Restore image */
val sys = input.readObject.asInstanceOf[T]
/* Restore commands */
try while (true)
input.readObject.asInstanceOf[(T) => _](sys)
catch { case endOfStreamReached: EOFException => }
sys
} else
initialState
}
private val journal = new ObjectOutputStream(new FileOutputStream(storageFile))
writeToJournal(system)
if (!pStorageFile.delete || !storageFile.renameTo(pStorageFile))
throw new IOException("Unable to rename " + storageFile + " to "
+ pStorageFile)
private def writeToJournal(any: Any) = {
journal.writeObject(any)
journal.flush
}
def executeTransaction[R](transaction: (T) => R) = synchronized {
writeToJournal(transaction)
transaction(system)
}
def executeQuery[R](query: (T) => R) = synchronized {
query(system)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment