2

I am going through book Java concurrency in practice

I came across the statement for volatile should be used in following criteria

  1. Writes to the variable do not depend on its current value, or you can ensure that only a single thread ever updates/writes the value.
  2. The variable does not participate in invariants with other state variables
  3. Locking is not required for any other reason while the variable is being accessed.

Can anyone explain me these three scenerios with example.

3
  • just google synchronization and volatile Commented Dec 22, 2016 at 11:37
  • To my understanding, volatile variables are loaded from actual memory every time it is called instead of loading from previous cache... hence the variable should not used for other purposes. In multi threaded env, there is possible for a thread can read the volatile data before another thread completes writing on it. Commented Dec 22, 2016 at 11:38
  • To understand the word volatile u will have to go through the memory model of java. An access to volatile variable introduces a memory barrier. And also compiler cannot optimize instruction around the access of the volatile variable. For reference this is pretty good read slideshare.net/michalwarecki/java-memory-model-23207253 Commented Dec 22, 2016 at 11:53

1 Answer 1

1

Answering your points:

  1. volatile is about reading the value; it ensures that writes are visible to all threads. It doesn't prevent write race conditions
  2. Atomicity of writes is on the field only; volatile does not provide coordination of writes to other fields
  3. No other actions are protected or included with the write
Sign up to request clarification or add additional context in comments.

3 Comments

please give examples.In interviews they ask for examples
@coder25 Examples would be situations as per my answer. I'm sure you can think of some. Also, if you can't think of some, you shouldn't apply for the job.
I would like to add that only with volatile it is visible to all threads but you dont know the exact time. @coder25 If you want to know more please read about it docs.oracle.com/javase/specs/jls/se7/html/jls-17.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.