如何在Kotlin中的方法上实现互斥并在一个线程之前优先处理另一个线程?

时间:2019-02-26 13:19:34

标签: kotlin mutex kotlin-coroutines

我有两个卡夫卡主题my_priorized_topicmy_not_so_priorized_topic。我想在EventProcessor.doLogic上使用互斥锁,并始终优先处理来自my_prioritized_topic的消息之前来自my_not_so_prioritized_topic的句柄消息

有人可以给我一些指导,如何用Kotlin(也许是协程)解决这个问题吗?

class EventProcessor {
  fun doLogic(message: String) {
    ... // code which cannot be parallelized
  }
}
class KafkaConsumers(private val eventProcessor: EventProcessor) {
  @KafkaConsumer(topic = "my_priorized_topic")
  fun consumeFromPriorizedTopic(message: String) {
    eventProcessor.doLogic(message)
  }

  @KafkaConsumer(topic = "my_not_so_priorized_topic")
  fun consumeFromNotSoPrioritizedTopic(message: String) {
    eventProcessor.doLogic(message)  
  }
}

1 个答案:

答案 0 :(得分:0)

您可以为高优先级任务和低优先级任务创建两个Channel。然后,要使用通道中的事件,请使用协程的select表达式,然后将高优先级任务通道放在首位。

示例(字符串是偶数):

fun process(value: String) {
    // do what you want with the event
}

suspend fun selectFromHighAndLow(highPriorityChannel: ReceiveChannel<String>, lowPriorityChannel: ReceiveChannel<String>): String =
        select<String> {
            highPriorityChannel.onReceive { value ->
                value
            }
            lowPriorityChannel.onReceive { value ->
                value
            }
        }


val highPriorityChannel = Channel<String>()
val lowPriorityChannel = Channel<String>()
while (true) {
    process(selectFromHighAndLow(highPriorityChannel, lowPriorityChannel))
}

要将内容发送到这些频道,可以使用channel.send(event)