paulblessing
01/05/2018, 6:46 PMclass ResourceManager<out T>(private val resource: T, readConcurrency: Int) {
private val readWriteLock = ReentrantReadWriteLock()
private val readContext = newFixedThreadPoolContext(readConcurrency, "reader")
private val writeContext = newSingleThreadContext("writer")
suspend fun <R> read(block: (T) -> R): R = withContext(readContext) {
readWriteLock.readLock().withLock { block(resource) }
}
suspend fun <R> write(block: (T) -> R): R = withContext(writeContext) {
readWriteLock.writeLock().withLock { block(resource) }
}
}
Going this way seems to do the trick pretty well, though I still have a dirty feeling about using the locks since they'll block. Maybe that's OK since these are all background threads but I haven't fully convinced myself that there aren't gotchas.radityagumay
01/06/2018, 12:29 PM