I am an analog guy learning how to code on android so please bear with me if this question sounds stupid.
I understand the gist of synchronization. If i have data that two threads can access and modify it could lead to inconsistent values in the data variable in both threads.
It makes sense to make methods synchronized and lock them till one thread is done executing it (performing any conditional checks) but why would it matter with single statements? It would matter with multiple statements as theres a chance of thread one going out of runnable state in between 2 or more statements but i dont understand what the point is for a single statement.
Here is an example
if i have a listener that can be called from lets say a game thread and it modifies a data variable why would i do it this way...
public void onCompletionListener(MediaPlayer player){
synchronized (this){
isPrepared = false;
}
}
i also have another method in my Music class called stop
public void stop(){
mediaPlayer.stop()
synchronized(this){
isPrepared = false;
}
}
Why would i bother to do this? Is this done for consistency of the value between the two threads? if so can i use something like volatile? would that be better?
I ask because i heard that synchronization is expensive. Are there better alternatives?
Thank you all in advance for answering my question. I appreciate it. Edit: I read this synchronization on single statement?
I think i understand.. if someone could elaborate that would be awesome. Also part two of my initial question regarding whether volatile is a better alternative is unanswered :)