I just came across a piece of code in akka.
https://codereview.scala-lang.org/fisheye/browse/~raw,r=25521/scala-svn/scala/trunk/test/files/presentation/akka/src/akka/util/LockUtil.scala
The core methods I am interested in is listed below.
/**
* A very simple lock that uses CCAS (Compare Compare-And-Swap)
* Does not keep track of the owner and isn't Reentrant, so don't nest and try to stick to the if*-methods
*/
class SimpleLock {
val acquired = new AtomicBoolean(false)
def ifPossible(perform: () => Unit): Boolean = {
if (tryLock()) {
try {
perform
} finally {
unlock()
}
true
} else false
}
def tryLock() = {
i开发者_运维百科f (acquired.get) false
else acquired.compareAndSet(false, true)
}
def tryUnlock() = {
acquired.compareAndSet(true, false)
}
There are two related subquestions.
1) What's purpose of this class SimpleLock
2) Any hints or background knowledge about how it works?
I think since this code is written in both JAVA and scala, it leverages the AtomicBoolean class. So I'd add java tag also.
Any advice is welcome! Not sure why someone vote this question close.
Related:
Can anyone interpret this C++ code (from OpenJDK6) into plain English?
Here is my understanding of the code. It used a acquired(AtomicBoolean) as a mutex. If any thread tries to acquire the lock , then it will set acquired to be true. then any other thread cannot acquired the lock due to they will get true from acquired and returned false until this acquired is set back to false by this thread.
Since acquired is not from a collection, it will not have ABA problem. So it can work.
Please correct me if I am wrong.
精彩评论