0

我刚刚在akka中遇到了一段代码。

https://codereview.scala-lang.org/fisheye/browse/~raw,r=25521/scala-svn/scala/trunk/test/files/presentation/akka/src/akka/util/LockUtil.scala

下面列出了我感兴趣的核心方法。

/**
 * 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() = {
    if (acquired.get) false
    else acquired.compareAndSet(false, true)
  }

  def tryUnlock() = {
    acquired.compareAndSet(true, false)
  }

有两个相关的子问题。

1)这个类SimpleLock的目的是什么

2)关于它如何工作的任何提示或背景知识?

我认为由于这段代码是用 JAVA 和 scala 编写的,因此它利用了 AtomicBoolean 类。所以我也会添加java标签。

欢迎任何建议!不知道为什么有人投票关闭这个问题。

有关的:

任何人都可以将这个 C++ 代码(来自 OpenJDK6)解释成简单的英语吗?

4

1 回答 1

1

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.

于 2011-09-06T05:03:16.490 回答