forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ThreadLockDemo.java
29 lines (27 loc) · 917 Bytes
/
ThreadLockDemo.java
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
package deadlock;
public class ThreadLockDemo {
/*
* This method request two locks, first Integer and then String
* */
public void method1() {
synchronized (Integer.class) {
System.out.println("Acquired lock on Integer.class object");
}
synchronized (String.class) {
System.out.println("Acquired lock on String.class object");
}
}
/*
* This method request two locks also, but in oppsite order.
* This creates potential deadlock, if one thread holds String lock and other holds Integer lock
* and they wait for each other, forever.
* */
public void method2() {
synchronized (String.class) {
System.out.println("Acquired lock on String.class object");
}
synchronized (Integer.class) {
System.out.println("Acquired lock on Integer.class object");
}
}
}