Menu

Two Bank Transfers at Once: Transactions, Explained
📰

Two Bank Transfers at Once: Transactions, Explained

DEV Community: java·Ravindra Singh·3 days ago
#VucRUZ7g
#devtojava#devto#dev#spring#lock
Long article (1605 words) — no AI summary yet.
Reading 0:00
15s threshold

Your account has ₹1,000. Two payments go out at the exact same moment: ₹500 and ₹300. You'd expect ₹200 left. The bank's database says ₹700 .

Nobody hacked anything. Two transfers read the same old balance, each saved its own answer, and the second save wiped out the first. That's called a lost update , and the cure is a database transaction that makes the second transfer wait its turn.

Let's watch it go wrong, then watch the same scene done safely.

The code that looks fine

Here's a withdraw method you'll find in a lot of first Spring Boot projects:

public void withdraw ( Long id , BigDecimal amount ) { Account acc = accounts . findById ( id ) . orElseThrow ( ) ; // 1. read acc . setBalance ( acc . getBalance ( ) . subtract ( amount ) ) ; // 2. work it out in Java accounts . save ( acc ) ; // 3. write }

Enter fullscreen mode

Exit fullscreen mode

Read, subtract, save. Run it once and it's perfect.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.