-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAvoidingDeadlocks.java
More file actions
62 lines (46 loc) · 2.01 KB
/
AvoidingDeadlocks.java
File metadata and controls
62 lines (46 loc) · 2.01 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
public class AvoidingDeadlocks {
// Shared resources
public static final Object resource1 = new Object();
public static final Object resource2 = new Object();
// Method to access resources in a specific order
public static void accessResources(String threadName) {
// Determine locking order based on hash codes
Object firstResource = (System.identityHashCode(resource1) < System.identityHashCode(resource2))
? resource1 : resource2;
Object secondResource = (firstResource == resource1) ? resource2 : resource1;
// Acquire the first resource
synchronized (firstResource) {
System.out.println(threadName + " acquired " + firstResource);
try {
Thread.sleep(100); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Acquire the second resource
synchronized (secondResource) {
System.out.println(threadName + " acquired " + secondResource);
try {
Thread.sleep(100); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(threadName + " is working with both resources.");
}
System.out.println(threadName + " released " + secondResource);
}
System.out.println(threadName + " released " + firstResource);
}
public static void main(String[] args) throws InterruptedException {
// Create and start threads
Thread t1 = new Thread(() -> accessResources("Thread-1"));
Thread t2 = new Thread(() -> accessResources("Thread-2"));
Thread t3 = new Thread(() -> accessResources("Thread-3"));
t1.start();
t2.start();
t3.start();
// Wait for threads to finish
t1.join();
t2.join();
t3.join();
}
}