This is one of questions asked to me in one of the technical talks.
public class MyClass {
volatile int i;
}
I am using the above MyClass as a ThreadLocal, so what is the use of taking any volatile variable inside this?
final ThreadLocal<MyClass> threadLocal = new ThreadLocal<MyClass>();
If that instance is used exclusively with ThreadLocal
and not passed around, there doesn't appear to be much point in volatile
.
Note, however, that MyClass
is just a class like any other: there's nothing preventing it from being used in contexts not involving thread-local storage. In those contexts it could well make sense for the variable to be volatile
.