2

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:

  1. the int value 100 which is held by the MutableObject
  2. the reference to the MutableObject held by the ArrayList

Thanks for answering.

4

2 回答 2

2

This code is thread-safe because there is not way that any other thread will access the same objects because they are available inside methodA() and in method run() of your thread. Both do not change the data.

Thread safety problems appear when at least 2 threads operate the same data. This is not your case.

How to make you code thread-unsafe? There are several ways.

  1. add line mo.setSomeValue(100); after calling t.start(). This means that after staring the thread there are 2 threads (your main thread and your other thread) that operate the same object mo. This will no however cause exceptions.

  2. add line mutableList.remove(0). This may cause ConcurrentModificationException if your thread starts quickly enough and manages to enter the loop before main thread arrives to remove instruction.

于 2013-05-14T13:04:52.490 回答
0

这里没有线程安全的问题。对象momutableList都在函数调用中定义和实例化。每次调用该函数时,都会创建 2 个新对象(如上)。没有任何线程不安全的值。

于 2013-05-14T13:08:57.577 回答