user1953478 user1953478 - 4 months ago 13
Android Question

Why Synchronize single statements in Java?

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

Answer

It is done because synchronization also puts in place requirements about memory visibility between threads.

If that write is not synchronized or volatile, there aren't any hard and fast requirements about when it becomes visible to other threads. Another thread could have a copy of isPrepared in its stack that says true, and it could run forever without knowing to go back to main memory and check if someone else has changed isPrepared if there's no synchronization or volatile reference.

The volatile keyword would satisfy the immediate requirement of making sure other threads see the update. It is impossible to say without seeing the entire class/system if it would be an acceptable replacement. It could be that there are other synchronized methods and it is illegal to change the state of isPrepared while one of them is mid-execution. Clearly it would then be an error to remove the synchronization in favour of a volatile reference.