-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathCounterExample.java
More file actions
61 lines (51 loc) · 1.8 KB
/
Copy pathCounterExample.java
File metadata and controls
61 lines (51 loc) · 1.8 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package org.alxkm.antipatterns.forgottensynchronization;
/**
*
* Forgotten synchronization is a common concurrency issue in Java where a method or block of code that should be synchronized is not,
* potentially leading to inconsistent data states or race conditions. Here's an example demonstrating this problem along with a resolution.
*
*
* In this example, the increment method and the getCount method are not synchronized,
* leading to potential race conditions when accessed by multiple threads simultaneously.
*
*/
public class CounterExample {
private int counter = 0;
/**
* Increments the counter by one.
* This method is not synchronized, leading to potential race conditions.
*/
public void increment() {
counter++;
}
/**
* Returns the current value of the counter.
* This method is not synchronized, which may result in reading an inconsistent value.
*
* @return the current count value.
*/
public int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
CounterExample counter = new CounterExample();
// Create two threads that both call increment 1000 times
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
// Wait for threads to finish
t1.join();
t2.join();
// This will likely print a number less than 2000 due to race conditions
System.out.println("Final Counter Value (without synchronization): " + counter.getCounter());
}
}