Nowak
04/29/2022, 1:34 PMNowak
04/29/2022, 1:47 PMphldavies
04/29/2022, 3:12 PMMutableMap<EntityId, Job>
using map.compute(key) { _, exist -> launch { exist?.join(); doWork() }
and a periodic map.values.removeIf { it.isCompleted }
- wasn’t overly happy as I’m sure there’s a better way but it seems to do the job.Nowak
04/29/2022, 3:38 PMclass MutexSerializedCommandHandler<C, R>(
private val handler: CommandHandler<C, R>,
private val keyProvider: (command: C) -> Any,
) : CommandHandler<C, R> {
private val mutexCache: AsyncCache<Any, Mutex> = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterAccess(Duration.ofSeconds(60))
.buildAsync()
override suspend fun handle(command: C): Result<R> = resultOf {
val key = keyProvider(command)
val keyMutex = mutexCache.get(key) { k -> Mutex() }.await()
return keyMutex.withLock(key) { handler.handle(command) }
}
}
tseisel
04/29/2022, 6:11 PM