Skip to content

Commit

Permalink
Merge pull request #15 from sungjuc/master
Browse files Browse the repository at this point in the history
Concurrency issues of atomicCreateIfAbsent function
  • Loading branch information
Raymond Ng committed May 15, 2013
2 parents 1c08f3f + f0ddf5f commit 50b42ca
Showing 1 changed file with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ package object norbertutils {

// TODO: Put this into a utility somewhere? Scala's concurrent getOrElseUpdate is not atomic, unlike this guy
def atomicCreateIfAbsent[K, V](map: ConcurrentMap[K, V], key: K)(fn: K => V): V = {
val oldValue = map.get(key)
if(oldValue == null) {
map.synchronized {
map.synchronized {
val oldValue = map.get(key)
if(oldValue == null) {
val newValue = fn(key)
map.putIfAbsent(key, newValue)
map.get(key)
} else {
oldValue
}
} else {
oldValue
}
}

Expand Down Expand Up @@ -99,4 +99,4 @@ package object norbertutils {
case e : Exception => // nothing
}
}
}
}

0 comments on commit 50b42ca

Please sign in to comment.