What the keyword volatile means in Java?

Luiz Gustavo De O. Costa
1 min readJul 13, 2019

--

What means?

Means that your thread always will work with memory values instead of local copies.

When should I apply?

As said before, only and only use volatile for attributes, you can want the behavior for methods and blocks, you should use synchronized.

What is the behavior?

The behavior as the Java documentation says is:

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.

The image bellow illustrate this behavior.

volatile in action

This is for multithreading environment and in this context, the thread always will work with memory value not with your own.

Example of declaration into a multithreading environment. This code only show the declaration.

Thank you for your time :)

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet