EdgeCampus keeps a "compute credit" account per research group. Transfers run concurrently on a thread pool; each transfer must lock both accounts, and must never deadlock.
Input: first line nAccounts nThreads; second line the initial balances of accounts 0…nAccounts−1; then transfers from to amount until the end of input (overdrafts are allowed; from ≠ to).
Requirements:
- Use one
ReentrantLockper account and anExecutorServicewithnThreadsthreads; submit one task per transfer. - Each task locks the two accounts in increasing account number order (to prevent deadlock), moves the amount, unlocks in
finally. - Wait for all tasks (
shutdown+awaitTermination), then printaccount i: balancefor every account,Total before: X,Total after: YandConservation: OKif equal, elseConservation: BROKEN, andTransfers: n.
Because every transfer is applied exactly once and addition is commutative, the final balances are deterministic even though the order of execution is not.
Input:
3 4
100 50 0
0 1 30
1 2 20
2 0 5
1 0 10
Output:
account 0: 85
account 1: 50
account 2: 15
Total before: 150
Total after: 150
Conservation: OK
Transfers: 4