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.


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles