44
55class Test {
66 public final Object lock = new Object ();
7-
7+
88 public volatile boolean aField = true ;
9-
9+
1010 public synchronized void bad1 (Resource r ) {
1111 // probably used concurrently due to synchronization
1212 if (r .getState ()) {
13- r .act ();
13+ r .act (); // $ Alert
1414 }
1515 }
1616
1717 public synchronized void bad2 (Resource2 r ) {
1818 // probably used concurrently due to synchronization
1919 if (r .getState ()) {
20- r .act ();
20+ r .act (); // $ Alert
2121 }
2222 }
2323
2424 public void bad3 (Resource r ) {
2525 // probably used concurrently due to use of volatile field
2626 if (r .getState () && aField ) {
27- r .act ();
27+ r .act (); // $ Alert
2828 }
2929 }
3030
3131 public void bad4 (Resource r ) {
3232 // probably used concurrently due to synchronization
3333 synchronized (this ) {
3434 if (r .getState () && aField ) {
35- r .act ();
35+ r .act (); // $ Alert
3636 }
3737 }
3838 }
39-
39+
4040 public void good1 (Resource r ) {
4141 // synchronizes on the same monitor as the called methods
4242 synchronized (r ) {
@@ -45,15 +45,15 @@ public void good1(Resource r) {
4545 }
4646 }
4747 }
48-
48+
4949 public Resource rField = new Resource ();
50-
50+
5151 public void someOtherMethod () {
5252 synchronized (lock ) {
5353 rField .act ();
5454 }
5555 }
56-
56+
5757 public void good2 () {
5858 // r is always guarded with the same lock, so okay
5959 synchronized (lock ) {
@@ -77,43 +77,43 @@ public void good3(Resource r) {
7777 r .act ();
7878 }
7979 }
80-
80+
8181 class Resource {
8282 boolean state ;
83-
83+
8484 public synchronized void setState (boolean newState ) {
8585 this .state = newState ;
8686 }
87-
87+
8888 public synchronized boolean getState () {
8989 return state ;
9090 }
91-
91+
9292 public synchronized void act () {
9393 if (state )
9494 sideEffect ();
9595 else
9696 sideEffect ();
9797 }
98-
98+
9999 public void sideEffect () { }
100100 }
101101
102102 class Resource2 {
103103 boolean state ;
104-
104+
105105 public void setState (boolean newState ) {
106106 synchronized (this ) {
107107 this .state = newState ;
108108 }
109109 }
110-
110+
111111 public boolean getState () {
112112 synchronized (this ) {
113113 return state ;
114114 }
115115 }
116-
116+
117117 public void act () {
118118 synchronized (this ) {
119119 if (state )
@@ -122,7 +122,7 @@ public void act() {
122122 sideEffect ();
123123 }
124124 }
125-
125+
126126 public void sideEffect () { }
127127 }
128128}
0 commit comments