Wednesday, May 4, 2011

volatile in Java, in multithreaded programs

Read the exercise in "extends Activity implements Runnable", concern about the variable running, without modifier:

boolean running;

It's a pitfall here, refer to the article http://java.sun.com/docs/books/jls/third_edition/html/memory.html (near the end of the article)

For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

 while (!this.done)
Thread.sleep(1000);


The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.


Also refer to the article http://java.sun.com/docs/books/jls/third_edition/html/classes.html, 8.3.1.4 volatile Fields.

the Java programming language allows threads to access shared variables. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

A field may be declared volatile, in which case the Java memory model ensures that all threads see a consistent value for the variable.


So, the variable running should be declared as volatile.

volatile boolean running;





No comments: