I'm having a little difficulty understanding volatile variables in Java.
I have a parameterized class that contains a volatile variable like so:
public class MyClass<T> {
private volatile T lastValue;
// ... other code ...
}
I have to implement certain basic operations against lastValue
including a get-value-if-not-null.
Do these operations need to be synchronized? Can I get away with doing the following method?
public void doSomething() {
String someString;
...
if (lastValue != null) {
someString += lastValue.toString();
}
}
Or do I need to stick the null check into a synchronized block?
public void doSomething() {
String someString;
...
synchronized(this) {
if (lastValue != null) {
someString += lastValue.toString();
}
}
}
I know that for atomic operations like get and set, I should be ok without applying synchronization (eg. public T getValue() { return lastValue; }
). But I wasn't sure about non-atomic operations.
someString += lastValue.toStrin();
assomeString += (""+lastValue);
lets you get rid of thenull
check altogether. – Essex