I am curious if the following code is thread-safe:
public static void methodA () {
// given that mutableObject is not thread-safe (no lock/synchronization used)
MutableObject mo = new MutableObject();
mo.setSomeValue(100); // set an int value
// the mutableList variable must be final in order to pass it to the thread block
final List<mutableObject> mutableList = new ArrayList<mutableObject>();
mutableList.add(mo);
Thread t = new Thread() {
@Override
public void run() {
for (mutableObject e : mutableList) {
e.printIntValue(); // print 100 or 0?
}
}
}
t.start();
}
so, here is the question. I am not sure whether all contents reachable* from the "mutableList" reference are visible to the new thread even though there is no explicit synchronization/locking used. (visibility issue) In other words, would the new thread print 0 or 100? it would print 0 if it does not see the value 100 set by the main thread as 0 is the default primitive value of the int data type.
ie. "contents reachable" means:
- the int value 100 which is held by the MutableObject
- the reference to the MutableObject held by the ArrayList
Thanks for answering.