0

我有一个用于获取和释放文件锁的类。我使用一个 customKey 类,它只是一个带有 id 字符串的 ReentrantReadWriteLock(id 是文件)。出于某种原因,这仅在某些情况下有效,并且在大多数情况下它会挂起所有东西的解锁 - 我的调试器跟踪它一直使用到那里然后就卡住了。

我究竟做错了什么?如果一个线程崩溃并且没有释放它的锁,我会得到,但是这里一个线程试图调用解锁并且没有进一步。

这是锁定的方法:

override fun acquire(lockId: String?, ownerId: String?, sequence: Long): Boolean
{
    if (lockId != null)
    {
        lockedList.find { customLock -> customLock.Id == lockId }.apply {
            if (this != null) //lock already exists for this ID
            {
                println("Locking file $lockId Existing lock")
                this.writeLock().lock()
                println("Locked file $lockId")
            } else //lock does not exist
            {
                val newLock = CustomLock(lockId)
                lockedList.add(newLock)
                println("Locking file $lockId")
                newLock.writeLock().lock()
                println("Locked file $lockId")
            }
        }
        return true
    } else
    {
        throw InvalidParameterException("ERROR: lockId or ownerId is null!")
    }
}

这是释放的方法:

override fun release(lockId: String?, ownerId: String?)
    {
        if (lockId != null)
        {
            lockedList.find { customLock -> customLock.Id == lockId }.apply {
                if (this != null)
                {
                    println("Unlocking file $lockId")
                    this.writeLock().unlock()
                    if (this.isWriteLocked)
                    {
                        throw Exception("ERROR: Unlocking failed!")
                    }
                } else
                {
                    throw Exception("ERROR: Lock not found!")
                }
            }
        }
    }

请不要费心谈论架构,这是由作业决定的。另外请忽略 ownerId 和 sequence 变量。

编辑:我尝试只使用一个锁,虽然效率不高,但它确实有效,所以@gidds 可能在某些东西上,但 ConcurrentHashMap 和 ConcurrentLinkedQueue (替换 List 更简单)都没有解决问题。

EDIT2:这是我使用 ConcurrentHashMap 的新类。它仍然无法正常工作,谁能指出我搞砸了?谢谢

class LockServer(port: Int) : LockConnector, RemoteException()
{
private val lockedList = ConcurrentHashMap<String, CustomLock>()
private var registry: Registry = LocateRegistry.createRegistry(port)

init
{
    registry.bind(ServiceNames.LockService.toString(), UnicastRemoteObject.exportObject(this, port))
}

/**
 * Method acquire() should block the multiple calls from the clients for each specific lockId string.
 * It means when one client acquires the lock "A" and the "A" is not locked by any other clients,
 * the method should record the lock and return true. If the "A" is already locked by any other client,
 * the method is blocked and continues only after the lock "A" is released.
 * (Note: Return value false is not used in this basic implementation.
 * Parameters ownerId and sequence are also not used in this basic implementation.)
 */
override fun acquire(lockId: String?, ownerId: String?, sequence: Long): Boolean
{
    if (lockId != null)
    {
        lockedList.computeIfPresent(lockId){id, value ->
            println("Locking file $id Existing lock")
            value.writeLock().lock()
            println("Locked file $id")
            return@computeIfPresent value
        }
        lockedList.computeIfAbsent(lockId){
            val newLock = CustomLock(it)
            println("Locking file $lockId")
            newLock.writeLock().lock()
            println("Locked file $lockId")
            return@computeIfAbsent newLock
        }
        return true
    } else
    {
        throw InvalidParameterException("ERROR: lockId or ownerId is null!")
    }
}

/**
 * Method release() should release the lock and unblock all waiting acquire() calls for the same lock.
 * (Note: Parameter ownerId is not used in this basic implementation.)
 */
override fun release(lockId: String?, ownerId: String?)
{
    if (lockId != null)
    {
        lockedList.computeIfPresent(lockId){ id, value ->
            println("Unlocking file $id")
            value.writeLock().unlock()
            println("Unlocked file $id")
            return@computeIfPresent value
        }
    }
}

/**
 * Method stop() unbinds the current server object from the RMI registry and unexports it.
 */
override fun stop()
{
    registry.unbind(ServiceNames.LockService.toString())
}

}

EDIT3:获取的新实现:

lockedList.compute(lockId){id, value ->
            if (value == null)
            {
                println("Locking file $id")
                val newLock = CustomLock(id)
                newLock.writeLock().lock()
                println("Locked file $id")
                return@compute newLock
            }
            println("Locking file $id Existing lock")
            value.writeLock().lock()
            println("Locked file $id")
            return@compute value
        }

和释放:

println("Unlocking $lockId")
        lockedList[lockId]!!.writeLock().unlock()
        println("Unlocked $lockId")

还是同样的失败

4

2 回答 2

1

这可能不是您的问题,但是在添加新锁时代码存在竞争条件:如果两个线程尝试锁定同一个(新)文件,它们都可以为它创建一个锁。两个锁都会被添加到列表中,但之后只会找到第一个。(这假定列表本身是线程安全的;否则其中一个添加可能会失败、永远循环,或者使列表处于不一致的状态并稍后崩溃。)

你可以通过一些同步来解决这个问题。但更好的方法可能是将锁存储在ConcurrentHashMap(以锁 ID 为键)而不是列表中,并使用诸如computeIfAbsent()之类的原子操作来安全地创建新锁。(这也会提高渐近性能,因为它可以避免每次都扫描一个列表。)

此外,作为风格问题,apply()锁上的使用看起来有点尴尬。(它通常用于自定义新创建的对象。)我认为let()那里会更惯用;你只需要换thisit里面。当然,或者使用老式的临时变量。

于 2020-10-06T11:06:28.763 回答
1

这可能不是 LockServer 类的问题,而是使用它的问题:

线程1:

acquire("file1")
acquire("file2")
release("file2")
release("file1")

线程2:

acquire("file2")
acquire("file1")
release("file1")
release("file2")

碰巧执行顺序如下:

thread1.acquire("file1")
thread2.acquire("file2")
thread1.acquire("file2") //locked by thread2, waiting
thread2.acquire("file1") //locked by thread1... BOOM, deadlock!

升级版:

考虑使用tryLock()(可能有一些超时)而不是简单lock()的现有锁:

    fun tryAcquire(lockId: String?, timeout: Long, unit: TimeUnit): Boolean {
        if (lockId != null) {
            var success = false
            lockedList.compute(lockId) { id, value ->
                if (value == null) {
                    println("Locking file $id")
                    val newLock = CustomLock(id)
                    newLock.writeLock().lock()
                    success = true
                    println("Locked file $id")
                    return@compute newLock
                }
                println("Locking file $id Existing lock")
                val lock = value.writeLock()
                if (lock.tryLock() || lock.tryLock(timeout, unit)) {
                    success = true
                    println("Locked file $id")
                }
                return@compute value
            }
            return success
        } else {
            throw InvalidParameterException("ERROR: lockId or ownerId is null!")
        }
    }
于 2020-10-07T17:44:00.123 回答