Monday, April 13, 2015

Java: volatile and synchronized block


In this tutorial we explain when to use volatile modifier for the variable.

Example:

Any non-main UI threads can change status of connection to a given service.

protected volatile boolean serviceConnected = false;


Explanation:
Since the variable can be changed by multiple threads, this means that the variable should not, and will NOT be cached locally in the thread, but in the MAIN MEMORY.

Volatile does pretty much the same as wrapping the variable in synchronized block, with few exceptions:

  • Unlike synchronized, the volatile can be used with java primitives.
  • Volatile allows NULL values, since you synchronize on the reference 
  • Synchronized block does not allow NULL as is synchronize on actual object
  • Synchronized has blocking access that is updating when entering or exiting the block.