Skip to content

Instantly share code, notes, and snippets.

@lucianenache
Last active March 14, 2016 22:23
Show Gist options
  • Save lucianenache/9defede22e3529d6a8c3 to your computer and use it in GitHub Desktop.
Save lucianenache/9defede22e3529d6a8c3 to your computer and use it in GitHub Desktop.
/* proof of concept for non atomic method */
/* to fix this the call should be wrapped */
/* inside a synchronized block */
private var uidCount = 0L
def getUniqueId(): Long = {
uidCount = uidCount + 1
uidCount
}
/* wrap the insecure function in a thread */
def startThread() = {
val t = new Thread {
override def run() {
val uids =
for (i <- 0 until 10) yield getUniqueId()
println(uids)
}
}
t.start()
t
}
/* fixed version */
val x = new AnyRef {}
def getUniqueIdSync(): Long = x.synchronized {
uidCount = uidCount + 1
uidCount
}
def startSyncThread() = {
val t = new Thread {
override def run() {
val uids =
for (i <- 0 until 10) yield getUniqueId()
println(uids)
}
}
t.start()
t
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment