Skip to content

Instantly share code, notes, and snippets.

@scottstewartt
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottstewartt/692c6f13bf07bdfb6db3 to your computer and use it in GitHub Desktop.
Save scottstewartt/692c6f13bf07bdfb6db3 to your computer and use it in GitHub Desktop.
Simple scala class for automatically reloading properties from file
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