Last active
August 29, 2015 14:19
-
-
Save scottstewartt/692c6f13bf07bdfb6db3 to your computer and use it in GitHub Desktop.
Simple scala class for automatically reloading properties from file
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
class PropsLoader(val filePath:String, val defaults:Map[String, String] = Map(), val reloadSecs:Int = 5) { | |
import java.util.concurrent.atomic._ | |
private val file = new java.io.File(filePath) | |
if (!file.isFile) throw new IllegalArgumentException(s"'$filePath' at ${file.getAbsolutePath} is not a file") | |
private var javaProps = new java.util.Properties | |
@volatile //synchronizes, could add thread-local cache | |
private var props = defaults | |
private val lastLoadCheck = new AtomicLong(-1) | |
private val fileLastModified = new AtomicLong(-1) | |
def sync = { | |
val now = System.currentTimeMillis | |
if ((now - lastLoadCheck.getAndSet(now))/1000 >= reloadSecs) { | |
val lm = file.lastModified | |
if (lm > fileLastModified.getAndSet(lm)) { | |
val fr = new java.io.FileReader(file) | |
javaProps.load(fr) | |
fr.close | |
props = defaults ++ javaProps | |
} | |
} | |
} | |
def get = { sync; props } | |
sync | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment