[concurrency-interest] Mixing volatile and synchronized together...

Jeremy Manson jmanson at cs.purdue.edu
Fri Oct 14 11:32:35 EDT 2005

Ryan LeCompte wrote:
> class Test {
>    private volatile boolean value = false;
>     synchronized void someOperation() {
>         // do something with "value"
>      }
> }
> In other words, there is no harm in using a volatile variable in a
> synchronized method or block, right?


Volatiles can actually be used anywhere fields with no modifiers can be 
used.  It would actually be semantically harmless to mark every field in 
your program volatile, if you wanted (BAD IDEA).  The program's results 
should be the same, for correctly written code.  The reasons it is a bad 
idea are: it would decrease performance, it would damage readability, 
and it probably wouldn't buy you the guarantees that you think it would 
buy you.

Now, as regards your case: it should be said that if you are using 
locking everywhere the volatile is accessed, then the volatile isn't 
going to provide additional assurances.  For this pattern to be useful, 
there would have to be another thread that accesses value without blocking.


More information about the Concurrency-interest mailing list