在进行三足交易时避免死锁

时间:2019-08-02 21:15:15

标签: spring kotlin accounting

在会计系统中,可以在帐户之间转移资金。

为避免在重复预订交易时出现僵局(帐户之间的转移),帐户之间的转移基于id顺序:

@Transactional
    override fun doubleBookPrepaid(eventId: Long, srcPurposefulAccountId: PurposefulAccountId, trgPurposefulAccountId: PurposefulAccountId, amount: Money): Pair<Money, Money>? =
        if (srcPurposefulAccountId.accountId < trgPurposefulAccountId.accountId) { // Locking minimal account ID first, to prevent deadlocks.
            val srcBooking = bookPrepaid(eventId, srcPurposefulAccountId, -amount)
            val trgBooking = bookPrepaid(eventId, trgPurposefulAccountId, amount)

            T(srcBooking, trgBooking)
        }
        else {
            val trgBooking = bookPrepaid(eventId, trgPurposefulAccountId, amount)
            val srcBooking = bookPrepaid(eventId, srcPurposefulAccountId, -amount)

            T(srcBooking, trgBooking)
        }

如何为三足交易完成相同的结果? 在这种交易中,一个帐户会在同一笔交易中将资金转移到两个帐户中:

data class PurposefulAccountTransfer(val trgPurposefulAccountId: PurposefulAccountId, val amount: Money)
    @Transactional
    fun threeLegBookPrepaid(eventId: Long, srcPurposefulAccountId: PurposefulAccountId, purposefulAccountTransfer: PurposefulAccountTransfer, secondPurposefulAccountTransfer: PurposefulAccountTransfer) {
        val srcBooking = bookPrepaid(eventId, srcPurposefulAccountId, -(purposefulAccountTransfer.amount + secondPurposefulAccountTransfer.amount))
        val trgFirstBooking = bookPrepaid(eventId, purposefulAccountTransfer.trgPurposefulAccountId, purposefulAccountTransfer.amount)
        val trgSecondBooking = bookPrepaid(eventId, secondPurposefulAccountTransfer.trgPurposefulAccountId, secondPurposefulAccountTransfer.amount)
    }

1 个答案:

答案 0 :(得分:0)

您只需要对所有命令进行排序以确保没有循环依赖性(假设T()接受vararg):

fun threeLegBookPrepaid(eventId: Long, ...) {
   val txs = sortedMapOf(
      srcAccountId  to bookPrepaid(eventId, srcAccountId , ...),
      trg1AccountId to bookPrepaid(eventId, trg1AccountId, ...),
      trg2AccountId to bookPrepaid(eventId, trg2AccountId, ...)
   )
   .map { it.component2() }
   .toTypedArray()

   T(*txs)
}

这可以很容易地推广到任意数量的帐户。