import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test implements Runnable{
private static SynchronizedInteger synchronizedInteger = new SynchronizedInteger();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
Runnable runnable = new Test();
executor.execute(runnable);
System.out.println("After runnable");
synchronizedInteger.set(100);
System.out.println("After set 100");
}
@Override
public void run() {
while(synchronizedInteger.get()!=100) {
System.out.println("not 100");
}
System.out.println("its 100");
}
}
I modified the class to following: public class SynchronizedInteger {
private int value;
public int get() {
return value;
}
public void set(int value) {
this.value = value;
}
}
But i never see such a case at least i tried running the code 20 times in Intellij Idea but it doesnt happen.
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
Runnable runnable = new Test();
Runnable runnable2 = new Test();
Runnable runnable3 = new Test();
executor.execute(runnable);
executor.execute(runnable2);
executor.execute(runnable3);
System.out.println("After runnable");
synchronizedInteger.set(100);
System.out.println("After set 100");
}
• this : The intrinsic lock of the object in whose class the field is defined.
• class-name.this : For inner classes, it may be necessary to disambiguate 'this'; the class-name.this designation allows you to specify which 'this' reference is intended
• itself : For reference fields only; the object to which the field refers.
• field-name : The lock object is referenced by the (instance or static) field specified by field-name.
• class-name.field-name : The lock object is reference by the static field specified by class-name.field-name.
• method-name() : The lock object is returned by calling the named nil-ary method.
• class-name.class : The Class object for the specified class should be used as the lock object.
And to clarify @GuardedBy, it is optional and it does not have any effect on the code
2) It specifies the the field "value" should only be accessed when a specified lock is held (in your case "this", i.e. the containing object (the object of which the field "value" is a member)).