I got such code:
public class ConcurrencyCheck {
private volatile static AtomicBoolean top=new AtomicBoolean(false);
private int i=0;
public class Toppler extends Thread{
private final boolean bool;
public Toppler(boolean myBool,String name) {
super(name);
bool=myBool;
}
@Override
public void run() {
while(!isInterrupted()){
i++;
synchronized (top) {
if (top.get() == bool) top.set(!top.get());
System.err.println(super.getName() + " "+ bool +"->" + top + ". i is " + i);
}
try {
sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
ConcurrencyCheck cc = new ConcurrencyCheck();
Thread t1= cc.new Toppler(true,"thread1");
Thread t2= cc.new Toppler(false,"thread2");
Thread t3= cc.new Toppler(true,"thread3");
Thread t4= cc.new Toppler(false,"thread4");
Thread t5= cc.new Toppler(true,"thread5");
Thread t6= cc.new Toppler(false,"thread6");
Thread t7= cc.new Toppler(true,"thread7");
Thread t8= cc.new Toppler(false,"thread8");
t1.start();
...
t8.start();
sleep(950);
t1.interrupt();
...
t8.interrupt();
}
}
It is designed to check how AtomicBoolean works. Class Toppler is a thread that periodically topples Atomic boolean. The block of code which topples boolean is synchronized. As I guessed, each output line have to topple value of "top" variable, so output have to be "true->false false->true true->false...". But for some reason sometimes I can see such output:
thread1 true->false. i is 1
thread8 false->true. i is 8
thread7 true->false. i is 8
thread4 false->true. i is 8
thread6 false->true. i is 8
thread3 true->false. i is 8
thread5 true->false. i is 8
thread2 false->true. i is 8
thread1 true->false. i is 9
thread8 false->true. i is 10
thread7 true->false. i is 11
thread4 false->true. i is 12
thread6 false->true. i is 13
thread3 true->false. i is 14
The question is: why two consequent false->true or true->false output lines are possible?