1

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...

Mr T
  • 506
  • 2
  • 9
  • 26

1 Answers1

1

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • So the answer is no. Thanks – Mr T Oct 25 '16 at 20:18
  • Well if you want to see it that way. I'd consider using `synchronized` a code smell at this day and age, since there are plenty of more efficient, more effective and easier methods of achieving your end result. – Kayaman Oct 25 '16 at 20:23