views:

88

answers:

2

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");
  }
 }
+3  A: 

No, reading a volatile variable is faster than than reading an non-volatile variable in a synchronized block.

A synchronized block clears the cached values on entry which is the same as reading a volatile variable. But, it also flushes any cached writes to main memory when the synchronized block is exited, which isn't necessary when reading volatile variable.

erickson
Ahh ok it makes sense now, thank you
Albinoswordfish
+1  A: 

There's a numebr of things wrong in your question: You can do a reliable read-update-write with volatile so long as you use Atomic*FieldUpdater and a cas-loop. Volatiles can be "cached", they just need to obey the relevant happens-before semantics specified.

Synchronisation typically involves obtaining a lock, which is relatively expensive (although may actually be quite cheap). Simple concurrent optimisations may use non-naive implementation techniques.

Tom Hawtin - tackline
After looking at the article again from Java 5 onwards it's possible
Albinoswordfish