Created
February 22, 2012 10:04
-
-
Save benshimmin/1883765 to your computer and use it in GitHub Desktop.
Simple lockfile implementation for AIR projects
This file contains hidden or 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
package { | |
import flash.filesystem.File; | |
import flash.filesystem.FileMode; | |
import flash.filesystem.FileStream; | |
public class LockFile { | |
private var lock : File; | |
private var lockData : String = "LOCKED: " + new Date().toTimeString(); | |
private var ensureAtomicity : Boolean; | |
private static var instance : LockFile; | |
public function LockFile(enforcer : SingletonEnforcer, lockStr : String, ensureAtomicity : Boolean) { | |
lock = new File(File.desktopDirectory.nativePath + File.separator + lockStr); | |
this.ensureAtomicity = ensureAtomicity; | |
writeLock(); | |
} | |
public static function createLock(lock : String = null, ensureAtomicity : Boolean = true) : void { | |
if (instance) { | |
trace("WARNING: You can only create one lockfile"); | |
} else { | |
if (!lock) { | |
throw new Error("Please provide a name for your lockfile"); | |
} | |
instance = new LockFile(new SingletonEnforcer(), lock, ensureAtomicity); | |
} | |
} | |
public static function checkLock() : Boolean { | |
return instance.lock.exists; | |
} | |
public static function removeLock(): void { | |
if (checkLock()) { | |
instance.lock.deleteFile(); | |
} | |
} | |
private function writeLock() : void { | |
if (ensureAtomicity) { | |
if (lock.exists) throw new Error("Lockfile already exists"); | |
} | |
var fs : FileStream = new FileStream(); | |
fs.open(lock, FileMode.WRITE); | |
fs.writeUTF(lockData); | |
fs.close(); | |
} | |
} | |
} | |
internal class SingletonEnforcer {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment