While reading the accepted answer How to synchronize or lock upon variables in Java?, it occurred to me if the behavior would change if one was to use volatile in the below example instead of synchronized block. I would like to make sure message always return the correct value.
Let me use this same sample: Note now I've removed the synchronized block in the get method and marked the variable message as volatile.
class Sample {
private volatile String message = null;
private final Object lock = new Object();
public void newMessage(String x) {
synchronized (lock) {
message = x;
}
}
public String getMessage() {
return message;
}
}
}
Would it warrant the same behavior if one was to change the code as shown above ?. Are there any differences between two approaches ?
Thank you in advance