view raw
Skemelio Skemelio - 6 months ago 33
Java Question

When a Thread acquires a lock are others able to invoke other methods?

Every java object has a built-in lock.
So if one of many threads wants to invoke a synchronized method it acquires the object's lock.

So let's assume that we have an object and two threads, t1 and t2.

The t1 thread asks for the object's lock to invoke the synchronized method object.methodA(). At the same time t2 asks the object's lock to invoke the synchronized method object.methodB().

Can this be done?

Is it possible for two threads to acquire the lock for two different methods? (Imagine an ideal scenario where methodA() and methodB() do not make operations on the same object fields)

If not, you are telling me that when a thread acquires the lock none of the others are able to invoke other synchronized methods even those who do not cost problems such as write to an object's field etc...


Making a method synchronized is just one of the ways you can control access. Multiple threads can't call a single object's synchronized methods at the same time (provided they're both the same static or non-static), so if you need more advanced control, there are plenty of other concurrency mechanisms such as ReadWriteLock.