-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathTest.java
More file actions
76 lines (64 loc) · 1.44 KB
/
Test.java
File metadata and controls
76 lines (64 loc) · 1.44 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
75
76
package examples;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@ThreadSafe
public class Test {
/**
* Escaping field due to public visibility.
*/
int publicField;
private int y;
final int immutableField = 1;
// As of the below examples with synchronized as well. Except the incorrectly placed lock.
private Lock lock = new ReentrantLock();
/**
* Calls the a method where y field escapes.
* @param y
*/
public void setYAgainInCorrect(int t) {
setYPrivate(t);
}
/**
* Locks the method where y field escapes.
* @param y
*/
public void setYAgainCorrect(int y) {
lock.lock();
setYPrivate(y);
lock.unlock();
}
/**
* No escaping y field. Locks the y before assignment.
* @param y
*/
public void setYCorrect(int y) {
lock.lock();
this.y = y;
lock.unlock();
}
/**
* No direct escaping, since it method is private. Only escaping if another public method uses this.
* @param y
*/
private void setYPrivate(int y) {
this.y = y; // $ Alert
}
/**
* Incorrectly locks y.
* @param y
*/
public void setYWrongLock(int y) {
this.y = y; // $ Alert
lock.lock();
lock.unlock();
}
public synchronized int getImmutableField() {
return immutableField;
}
public synchronized int getImmutableField2() {
return immutableField;
}
public void testMethod() {
this.y = y + 2; // $ Alert
}
}