Ok so I just read this question http://stackoverflow.com/questions/106591/do-you-ever-use-the-volatile-keyword-in-java, and I get using a volatile variable in order to stop a loop. Also I've seen this reference, http://www.javamex.com/tutorials/synchronization_volatile.shtml. Now the article says that volatile variables are non-blocking. Also it says that it cannot be used for concurrency in a read-update-write sequence. Which makes sense because they're non-blocking.
Since volatile variables are never cached is it faster to simply use synchronization to stop the loop (from the earlier link)?
Edit: Using a synchronized solution
public class A{
private boolean test;
public A(){
test = true;
}
public synchronized void stop(){
test = false;
}
public synchronized boolean isTrue(){
return test;
}
}
public class B extends Thread {
private A a;
public B(A refA){
a = refA;
}
public void run(){
//Does stuff here
try{
sleep(1000);
}
catch(Exception e){}
a.stop();
}
public static void main(String [] args){
A TestA = new A();
B TestB = new B(TestA);
TestB.start();
while(TestA.isTrue()){
//stay in loop
System.out.println("still in loop");
}
System.out.println("Done with loop");
}
}