Skip to content
This repository was archived by the owner on Feb 13, 2020. It is now read-only.
This repository was archived by the owner on Feb 13, 2020. It is now read-only.

Key-based mutex #126

Description

@jcornaz

Draft:

class KeyBasedMutex<in K>(size: Int) {

  private val mutexes = List(size) { Mutex() }

  init {
    require(size > 0)
  }

  suspend fun lock(key: K) {
    mutexes[key.hashCode() % mutexes.size].lock()
  }

  fun unlock(key: K) {
    mutexes[key.hashCode() % mutexes.size].unlock()
  }
}

suspend inline fun <K, R> KeyBasedMutex<K>.withLock(key: K, block: () -> R): R {
  lock(key)
  return try {
    block()
  } finally {
    unlock(key)
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureAdd a new featureneed-usecaseThis lacks of use-case for now. It has to be motivated by a concrete need before being implemented.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions