суббота, 30 июня 2018 г.

Java volatile keyword

According to Java Language Specification 8 section 8.3.1.4:
"As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes. 

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable" .

Please note, that volatile doesn't imply atomic.  So that if your code is like this:
private volatile int var = 0;
var = var+1;
and you run increment in 2 threads then result won't be 2 in all situations.
In other words volatile fix visibility problems but not race conditions.

I recommend to go by following link https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4 and take a look at example.

From Concurrent programming in Java 2nd:
  • Declaring a reference field as volatile does not ensure visibility of non- volatile fields that are accessed via this reference. 
  • Similarly, declaring an array field as  volatile does not ensure visibility of its elements. 
  • Volatility cannot be manually propagated for arrays because array elements themselves cannot be declared as volatile. 
Declaring fields as  volatile can be useful when you do not need locking for any other reason, yet
values must be accurately accessible across multiple threads. This may occur when:
  • The field need not obey any invariants with respect to others.
  • Writes to the field do not depend on its current value.
  • No thread ever writes an illegal value with respect to intended semantics.
  • The actions of readers do not depend on values of other non-volatile fields.

Комментариев нет:

Отправить комментарий