Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code after synchronized block in java

I've a simple question but couldn't manage to find a proper answer. Imagine we have;

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }

    nameList.add(name);
} 

What about the code after sync. block here? I mean sync. blocks are used to reduce scope of lock but here the code after it ( namelist.add(name) ) will be blocked, right ?

Assume thread A called this function above but it's gonna wait for 'this' lock to be released by thread B which had the lock before on some other method. Now, I wondered if the execution will resume from B's nameList.add(name) method while thread A is waiting on 'this' lock object - since nameList.add(name) is not in the sync block.

like image 961
stdout Avatar asked Oct 26 '25 15:10

stdout


1 Answers

Now, I wondered if the execution will resume from B's nameList.add(name) method while thread A is waiting on 'this' lock object - since nameList.add(name) is not in the sync block.

No, the thread executing the method can't just skip over the block and execute the remaining part of the method. What it will do is block until it can acquire the monitor on this, then execute the synchronized block, then release the monitor on this, then add the string to the nameList.

If concurrent threads execute this, there's no guarantee of which threads will insert into the nameList first. It's possible that between the time that a thread releases the monitor on this and the time that it adds to the nameList one or more other threads might barge in and add to the list.

Also whatever nameList is implemented as needs to be a thread-safe collection, so that concurrent changes don't cause errors and so that changes are visible across threads. If nameList is an ArrayList or a HashSet, for instance, then this would not be safe.

like image 127
Nathan Hughes Avatar answered Oct 29 '25 05:10

Nathan Hughes