Search⌘ K
AI Features

Solution: High-Frequency Bidding

Explore how to implement safe concurrent updates in a high-frequency bidding system using AtomicInteger for atomic operations, retry loops for conflict resolution, and multiple threads to simulate simultaneous bids. Learn to avoid locks while maintaining data integrity and controlling thread execution through start and join methods.

We'll cover the following...
Java 25
import java.util.concurrent.atomic.AtomicInteger;
public class HighFrequencyBidding {
static class AuctionItem {
// 1. Use AtomicInteger for lock-free thread safety
private AtomicInteger highestBid = new AtomicInteger(0);
public void submitBid(int bidAmount) {
while (true) {
// 2. Read the current state
int current = highestBid.get();
// 3. Check logic: Only update if new bid is strictly higher
if (bidAmount <= current) {
return; // Existing bid is already higher or equal; give up.
}
// 4. Attempt atomic update (CAS)
// If current value is still 'current', set it to 'bidAmount'.
// If success, return true. If fail (value changed), return false.
if (highestBid.compareAndSet(current, bidAmount)) {
// Success! We updated the value.
// System.out.println("New High Bid: " + bidAmount); // Optional log
return;
}
// 5. If compareAndSet failed, loop again immediately (Spin Lock)
}
}
public int getHighestBid() {
return highestBid.get();
}
}
public static void main(String[] args) {
AuctionItem item = new AuctionItem();
// 6. Define a heavy workload task
Runnable bidderTask = () -> {
for (int i = 0; i < 1000; i++) {
int randomBid = (int) (Math.random() * 1_000_000);
item.submitBid(randomBid);
}
};
// 7. Create multiple concurrent threads
Thread t1 = new Thread(bidderTask);
Thread t2 = new Thread(bidderTask);
Thread t3 = new Thread(bidderTask);
Thread t4 = new Thread(bidderTask);
Thread t5 = new Thread(bidderTask);
t1.start(); t2.start(); t3.start(); t4.start(); t5.start();
try {
// 8. Wait for everyone to finish
t1.join(); t2.join(); t3.join(); t4.join(); t5.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Highest Bid: " + item.getHighestBid());
}
}
...