All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin.concurrent.Locks.kt Maven / Gradle / Ivy

@file:JvmVersion
@file:JvmName("LocksKt")
package kotlin.concurrent

import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.concurrent.CountDownLatch

/**
 * Executes the given [action] under this lock.
 * @return the return value of the action.
 */
@kotlin.internal.InlineOnly
public inline fun  Lock.withLock(action: () -> T): T {
    lock()
    try {
        return action()
    } finally {
        unlock();
    }
}

/**
 * Executes the given [action] under the read lock of this lock.
 * @return the return value of the action.
 */
@kotlin.internal.InlineOnly
public inline fun  ReentrantReadWriteLock.read(action: () -> T): T {
    val rl = readLock()
    rl.lock()
    try {
        return action()
    } finally {
        rl.unlock()
    }
}

/**
 * Executes the given [action] under the write lock of this lock.
 * The method does upgrade from read to write lock if needed.
 * If such write has been initiated by checking some condition, the condition must be rechecked inside the action to avoid possible races.
 * @return the return value of the action.
 */
@kotlin.internal.InlineOnly
public inline fun  ReentrantReadWriteLock.write(action: () -> T): T {
    val rl = readLock()

    val readCount = if (writeHoldCount == 0) readHoldCount else 0
    repeat(readCount) { rl.unlock() }

    val wl = writeLock()
    wl.lock()
    try {
        return action()
    } finally {
        repeat(readCount) { rl.lock() }
        wl.unlock()
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy