I am trying to implement a lock(like basic read-write lock) based on the TMap.
object TMapLock {
val mapLock = TMap.empty[Any, Tuple3[String, Long, Int]].single
val txnType = collection.mutable.Map[InTxn, Tuple3[String, Long, Int]]()
def lock(key: Any, myLock: Tuple3[String, Long, Int]): Unit = {
atomic { implicit txn =>
val existLock = mapLock.get(key) match {
case Some(s) => s
case None => null
}
if (existLock != null) {
//check write/write conflit or read/write conflict
if (myLock._1.equals("write") || (existLock._1.equals("write") && myLock._1.equals("read")))
retry
}
//update the lock
mapLock.put(key, myLock)
}
}
def unlock(key: Any, myLock: Tuple3[String, Long, Int]): Unit = {
val existLock = mapLock.get(key) match {
case Some(s) => s
case None => null
}
//check if the lock is belongs to the current transaction
if (existLock != null && existLock._2 == myLock._2 && existLock._3 == myLock._3)
mapLock.remove(key)
}
def lockForTxnDuration(key: Any, lockType: String): Unit = {
implicit def txn = Txn.findCurrent.get
//first parameter is read/write lock type, second and third one is used to determine the lock owner
val myLock:Tuple3[String, Long, Int] = (lockType, System.nanoTime, txn.hashCode)
lock(key, myLock)
Txn.afterCompletion { _ => unlock(key, lockType) }
}
}
This implementation references your code in the previous post(shown below). But I think the code in that post could not be used in high lock contention and I try to improve it in the above way.
val lockHeld = Ref(false)
def lock(): Unit = atomic { implicit txn =>
//the transaction will infinitely in the loop here. It is still retrying though the lockHeld() is false
if (lockHeld()) retry
lockHeld() = true
}
def unlock(): Unit = {
lockHeld.single() = false
}
def lockForTxnDuration(): Unit = {
// I think 'def' should be added here?like implicit def txn = Txn.findCurrent.get ?
implicit txn = Txn.findCurrent.get
lock()
Txn.afterCompletion { _ => unlock() }
}
However, I am confused about the usage of TMap, and the implementation is faulty in somewhere. I tried to use it in the stmbench7, modified based on your code and my designed object(it works fine when I used an other simple lock instead). Can you indicates the mistakes in that TMapLock and fix the problem in the basic boolean lock?