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;
}
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With