Created
April 6, 2012 20:01
-
-
Save fwbrasil/2322553 to your computer and use it in GitHub Desktop.
PrevaylerJr in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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