First question: correct
Second case: yes, acts like a mutex
Third question: correct
Answer to the edit:
A synchronized
block uses its argument object as the lock (or, better, mutex) for the block. So that if two threads reach critical sections synchronized
on the same object, only one thread will be allowed to enter its critical section, while the other one waits until this one exits from the critical section.
A synchronized
method is just syntactic sugar for the synchronized
block so that
class SyncClass
{
public synchronized void process()
{
}
}
could be written as
class SyncClass
{
public void process()
{
synchronized(this)
{
// whole body of process() inside this block
}
}
}
So, to answer your questions
synchronized
will locklist
(or any other object used as its argument) globally, not just for a specific method. You can synchronize on an object anywhere in the code and the synchronized sections will run with mutual exclusion irrespective of the containing methods/classes or the call hierarchy, etc.processList1()
andprocessList2()
will not execute concurrently. Only one can execute at a time. (This assumes you have no code outside thesynchonized
blocks.)execute3()
and execute4() can execute concurrently but only up to the point they reach thesynchronized
sections. That is, calls toprocessList1()
andprocessList2()
and any code you have before these calls theexecute3/4()
methods can execute concurrently but code inside thesynchronized
sections cannot be executed concurrently.