Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.84 KB | None | 0 0
  1.  private inner class TransferOp(val fromIndex: Int, val toIndex: Int, val amount: Long) : Op() {
  2.  
  3.         var errorMessage: String? = null
  4.  
  5.         override fun invokeOperation() {
  6.             // todo: write implementation for this method, use TotalAmountOp as an example
  7.             /*
  8.              * In the implementation of this operation only two accounts (with fromIndex and toIndex) needs
  9.              * to be acquired. Unlike TotalAmountOp, this operation has its own result in errorMessage string,
  10.              * and it must also update AcquiredAccount.newAmount fields before setting completed to true
  11.              * and invoking release on those acquired accounts.
  12.              *
  13.              * Basically, implementation of this method must perform the logic of the following code "atomically":
  14.              */
  15.             val from: AcquiredAccount?
  16.             val to: AcquiredAccount?
  17.             if (fromIndex < toIndex) {
  18.                 from = acquire(fromIndex, this)
  19.                 to = acquire(toIndex, this)
  20.             } else {
  21.                 to = acquire(toIndex, this)
  22.                 from = acquire(fromIndex, this)
  23.             }
  24.             if (from != null && to != null) {
  25.                 if (amount > from.amount)
  26.                     errorMessage = "Underflow"
  27.                 else if (to.amount + amount > MAX_AMOUNT)
  28.                     errorMessage = "Overflow"
  29.                 else {
  30.                     from.newAmount = from.amount - amount
  31.                     to.newAmount = to.amount + amount
  32.                 }
  33.                 completed = true
  34.             }
  35.             if (fromIndex < toIndex) {
  36.                 release(fromIndex, this)
  37.                 release(toIndex, this)
  38.             } else {
  39.                 release(toIndex, this)
  40.                 release(fromIndex, this)
  41.             }
  42.         }
  43.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement