is a volatile variable synchronized? (java)
Asked Answered
N

6

8

Say that I have a private variable and I have a setVariable() method for it which is synchronized, isn't it exactly the same as using volatile modifier?

Nightdress answered 22/5, 2011 at 16:2 Comment(0)
M
7

No. Volatile means the variable isn't cached in any per-thread cache, and its value is always retrieved from main memory when needed. Synchronization means that those per-thread caches will be kept in sync at certain points. In theory, using a volatile variable can come with a great speed penalty if many threads need to read the value of the variable, but it is changed only rarely.

Mellen answered 22/5, 2011 at 16:8 Comment(1)
If some kind of synchronization is required, aren't you typically talking about speed penalties anyway? (Doesn't generally make much sense to synchronize writes if you're not synchronizing reads as well...)Brower
F
4

No, calling a synchronized getXXX/setXXX method is not the same as reading/writing to a volatile variable.

Multiple threads can concurrently read from or write to a volatile variable. But only one thread at a time can read from or write to a variable that is guarded by a synchronized block.

Fremitus answered 27/10, 2012 at 7:19 Comment(0)
B
1

volatile variables are not synchronized (at least, not in the way synchronized stuff is synchronized). What volatile does is ensure that a variable is retrieved each time it's used (ie: it prevents certain kinds of optimization), and IIRC that it's read and written in the correct order. This could conceivably emulate some kinds of synchronization, but it can't work the same if your setter has to set more than one thing. (If you set two volatile variables, for example, there will be a point where one is set and the other isn't.)

Brower answered 22/5, 2011 at 16:16 Comment(0)
R
0

Actually No.

volatile is actually weaker form of synchronization, when field is declared as a volatile the compiler and runtime understands that this variable is shared and operations on it shouldn't be reordered with other memory operations. Volatile variable aren't cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always return a recent write by any thread.

Rearm answered 22/5, 2011 at 16:16 Comment(0)
E
0

just an example :

First thread run  :
while(stopped){
 ... do something
}

Second thread run :
stopped = true;

it's useful to declare stopped as a volatile boolean for the first thread to have a fresh value of it.

Elgin answered 22/5, 2011 at 17:16 Comment(0)
L
0

There is no any relation.

Basically

  • Volatile => it always retrieves parameter's latest value
  • Synchronized => it serves only 1 thread at the same time
Licht answered 3/6, 2014 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.