-3

I understand volatile should be used on a class field to prevent the JVM from caching the value so when it will always be the latest value when it's read.

If my understanding is correct, doesn't it mean we should define all fields with volatile when working in a multithread thread-safe environment? When is it unnecessary to define a field as volatile?

Glide
  • 20,235
  • 26
  • 86
  • 135
  • *we should define all fields with volatile* Every field of every object? No. Only fields accessible to multiple concurrent threads. – shmosel Jun 16 '16 at 23:30
  • volatile prevents the JVM to optimize the code related to your variable, if you define all fields as volatile, you will lose a lots of performance. – Guillaume F. Jun 16 '16 at 23:39

1 Answers1

0

It is unnecessary to define a field volatile if that field won't be accessed by multiple threads without another mechanism to provide synchronisation (such as locks).

If every member of a class could get so accessed, then every field should be so marked.

John Burger
  • 3,662
  • 1
  • 13
  • 23