yotamoo
yotamoo

Reputation: 5452

is a volatile variable synchronized? (java)

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?

Upvotes: 8

Views: 2004

Answers (6)

Mustafa Güven
Mustafa Güven

Reputation: 15744

There is no any relation.

Basically

  • Volatile => it always retrieves parameter's latest value
  • Synchronized => it serves only 1 thread at the same time

Upvotes: 0

Nam San
Nam San

Reputation: 1245

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.

Upvotes: 4

EricParis16
EricParis16

Reputation: 809

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.

Upvotes: 0

Premraj
Premraj

Reputation: 7902

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.

Upvotes: 0

cHao
cHao

Reputation: 86506

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.)

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

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.

Upvotes: 7

Related Questions