Reputation: 2651
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.
Upvotes: 4
Views: 1880
Reputation: 96395
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.
Upvotes: 7
Reputation: 18420
synchronized(this)
will block if and while another thread is inside this block. If the thread leaves this block, one waiting thread has a chance (amongst other waiting threads) to enter the block. namelist.add()
is executed outside the synchronized scope, so it may be executed in parallel with other threads.
Upvotes: 0
Reputation: 2167
In principle, keyword synchronized
does following two things:
Code guarded by the synchronized keyword cannot be executed simultaneously by more than one thread;
.. it controls the visibility of data (variables) between threads;
In your example, the code which is not in synchronized
scope would be accessible by all other Threads which call this method;
Assuming the operations which is out of scope is writing operation, you'd (generally) want it to be synchronized
to reduce any anomalies which may creep up.
Upvotes: 0