paulblessing
01/05/2018, 3:53 PMn readers at any time, running on a pool of reader threads
- there can only be a single writer, running on a dedicated writer thread
- has ReadWriteLock rules where a writer needs exclusive access but readers can execute concurrently with each other
class ResourceManager<out T>(private val resource: T, readConcurrency: Int) {
private val readWriteLock = ReentrantReadWriteLock()
private val readExecutor: ListeningExecutorService =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(readConcurrency))
private val writeExecutor: ListeningExecutorService =
MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor())
fun <R> read(block: (T) -> R): ListenableFuture<R> = readExecutor.submit(Callable {
readWriteLock.readLock().withLock { block(resource) }
})
fun <R> write(block: (T) -> R): ListenableFuture<R> = writeExecutor.submit(Callable {
readWriteLock.writeLock().withLock { block(resource) }
})
}
The `ExecutorService`s take care of the threading and limiting of the number of concurrent readers, and the ReadWriteLock takes care of making sure the writer gets exclusive access.
Is there a way to convert read and write to `suspend fun`s, and still keep the same general behavior? A call to write would suspend while any other readers/writers are active, and then once those are finished, the block passed to write would be executed on the writer thread and then the caller would be resumed with its result (with the appropriate semantics for calls to read as well).