-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathAtomicCompoundActionsExample.java
More file actions
57 lines (47 loc) · 1.51 KB
/
Copy pathAtomicCompoundActionsExample.java
File metadata and controls
57 lines (47 loc) · 1.51 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
package org.alxkm.antipatterns.nonatomiccompoundactions;
/**
*
* To resolve this issue, we can synchronize the method to ensure that the compound action is atomic.
*
* In this revised example, the incrementIfLessThan method is synchronized,
* ensuring that the compound action is performed atomically.
* This prevents race conditions and ensures correct results.
*
*/
public class AtomicCompoundActionsExample {
private int counter = 0;
/**
* Increments the counter if it is less than a specified limit.
* This method is synchronized to ensure atomicity.
*
* @param limit the limit to check against.
*/
public synchronized void incrementIfLessThan(int limit) {
if (counter < limit) { // Check
counter++; // Then act
}
}
/**
* Returns the counter value.
*
* @return the counter value.
*/
public synchronized int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
AtomicCompoundActionsExample example = new AtomicCompoundActionsExample();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.incrementIfLessThan(10);
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Final counter value: " + example.getCounter());
}
}