Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does function returning a volatile variable need synchronization?

Tags:

java

volatile

setGameState() and getGameState() can be called from different threads. m_gameState is volatile so its value/change could be visible to other threads.

Question: Do the functions need to be synchronized or does volatile on the variable suffice?

private volatile EGameState m_gameState;

public void setGameState(EGameState a_gameState) {
   m_gameState = a_gameState;
}

public EGameState getGameState() {
   return m_gameState;
}
like image 791
MicroEyes Avatar asked Feb 23 '19 18:02

MicroEyes


2 Answers

Access to the volatile variable acts as though it is synchronized on itself.

Accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation.Here you are required to use a synchronized block.

For other cases it will suffice if you didn't use synchronization(like normal get and set)

like image 164
Vaibhav Gupta Avatar answered Oct 27 '22 10:10

Vaibhav Gupta


That depends. Do you require the updates of your EGameState field to be ordered or not?
If they must be ordered, than a synchronized block (on this) is mandatory, if not, volatile is sufficient.

like image 41
LppEdd Avatar answered Oct 27 '22 11:10

LppEdd