image

Cracking Core Java Interviews 3rd Edition

A Comprehensive Guide to Crack Core Java Interviews in Investment Banks, HealthCare IT & Startups. It covers Core Java, Algorithms, Data Structures, Concurrency, Hibernate and Spring MVC.

Specifically for investment banking domain, healthcare IT and product companies i.e. UBS, RBS, Blackrock, Morgan Stanley, JP Morgan, Nomura, Barclays, Citibank, Markit, Bank of America, Goldman Sachs and other companies i.e. Global Logic, Adobe, hCentive, Edifecs, Expedia, Infosys, TCS, Sapient, Wipro, HCL etc.
Free Chapters PDF
1460 downloads
Buy Full PDF ₹250
3rd Edition
Last Updated : Monday, March 14, 2016 9:21:51 AM IST Total Page Hits 1349

What does volatile keyword do in a multi-threading environment

Main Functions of volatile keyword -

  1. Reads and writes are atomic for all variables that are declared volatile. This includes long and double variables too (irrespective the architecture of the OS x64 or 32 bit)
  2. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What’s more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
  3. afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both).

Please be noted that Atomic actions cannot be interleaved, so they can be used without fear of thread interference.

Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. Whether the extra effort is worthwhile depends on the size and complexity of the application.

Oracle Documentation




Similar Articles

1. Synechron Java Interview Questions

Collection of Java Interview Questions (Core Java, Spring, database and other concepts) for Synechron in banking and finance domain

2. Design Metro Smart Card System for Delhi using Java

Design a program in Java for Metro Smart Card System in Delhi. Evaluation criteria will be based on code completeness, code structure and quality, modularity, usage of OO principles, choice of data structure and unit tests.

3. What does volatile keyword do in a multi-threading environment

volatile keyword helps programmers write thread safe program