Last active
March 14, 2016 22:23
-
-
Save lucianenache/9defede22e3529d6a8c3 to your computer and use it in GitHub Desktop.
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
/* 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