-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaceConditionDemo.java
More file actions
42 lines (34 loc) · 1.37 KB
/
RaceConditionDemo.java
File metadata and controls
42 lines (34 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 1. RACE CONDITION - Multiple threads accessing shared data without synchronization
// Problem: Two threads increment counter simultaneously, causing incorrect results
public class RaceConditionDemo {
static class Counter {
private int count = 0; // Shared resource without synchronization
public void increment() {
// Read count
// Increment (if count = 5, temp = 6)
// Write back to count
// Without synchronization, this is NOT atomic!
count++;
}
public int getCount() {
return count;
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// Create two threads that both increment the same counter 1000 times
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment(); // Race condition occurs here!
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join(); // Wait for both threads to finish
t2.join();
// Expected: 2000, but likely will be less due to race condition
System.out.println("Final count: " + counter.getCount() + " (Expected: 2000)");
}
}