-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaceCondition2FixedLock.java
More file actions
74 lines (71 loc) · 2.76 KB
/
RaceCondition2FixedLock.java
File metadata and controls
74 lines (71 loc) · 2.76 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
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* RaceCondition2FixedLock.java (Race Condition Version 2, Fixed with Mutex Locks)
*
* Written by Andrew Lui, The Open University of Hong Kong 2018
*
* Aim: This program uses the semaphore lock methods in Java to implement the critical section situation
*
* Instruction: (1) Observe how the lock is used. (2) Execute the program. (3) Note that no race condition should occur but the execution time is seems quite long
*
* The difference between the re-entrant lock and semaphore is the same thread can acquire the lock more than once (re-entrant).
* You may read more about this in Java Semaphore vs ReentrantLock: https://howtodoinjava.com/java/multi-threading/semaphore-vs-reentrantlock/
*/
public class RaceCondition2FixedLock {
private static Lock theLock;
static class Buffer {
static int value = 0;
}
static class TestProcessA implements Runnable {
public void run() {
try {
for (int i = 0; i < 1000000; i++) {
theLock.lock();
Buffer.value = Buffer.value + 1;
theLock.unlock();
}
} catch (Exception ex) {
} finally {
}
}
}
static class TestProcessB implements Runnable {
public void run() {
try {
for (int i = 0; i < 1000000; i++) {
theLock.lock();
Buffer.value = Buffer.value - 1;
theLock.unlock();
}
} catch (Exception ex) {
} finally {
}
}
}
public static void main(String args[]) throws Exception {
int testnum = 100;
int countError = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < testnum; i++) {
Buffer.value = 0;
theLock = new ReentrantLock();
Thread threadA = new Thread(new TestProcessA());
Thread threadB = new Thread(new TestProcessB());
threadA.start();
threadB.start();
threadA.join();
threadB.join();
if (Buffer.value != 0) {
System.out.println("[RUN " + i + "] Error found. value is " + Buffer.value);
countError++;
} else {
System.out.println("[RUN " + i + "] The threads have finished and no error found");
}
}
long endTime = System.currentTimeMillis();
long timeTaken = (endTime - startTime);
System.out.println("Number of errors due to race conditions: " + countError + " out of " + testnum + " epochs");
System.out.println("Time taken = " + timeTaken + " ms");
}
}