Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety - declaring a new thread inside method local block

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.

like image 841
ben ben Avatar asked Aug 09 '26 05:08

ben ben


1 Answers

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.

like image 89
AlexR Avatar answered Aug 10 '26 19:08

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!