0

I'm a newbie to threads and specifically the synchronized key word.

I understand that a thread's state changes to BLOCKED if it tried to access a synchronized block where another thread already owns the lock.

For reference:

synchronized (objA){
    objA.methodA();
}

//some code

objA.methodB();

My question is whether another thread can alter the object objA through another independent method (methodB() in this example). Or does owning the lock mean that no other thread can access/alter objA in any way ie whether or not the alteration code is within the synchronized block?

alwayscurious
  • 1,155
  • 1
  • 8
  • 18
  • is it then possible that a method which is not synchronized is called on `objA` while another thread owns the monitor? – alwayscurious Sep 01 '17 at 07:37
  • Yes. Any thread can call a non-synchronized method at any time, since it doesn't need to hold any lock to call it. – JB Nizet Sep 01 '17 at 07:38

2 Answers2

2

No. The only thing that owning the monitor (lock) means, is that no other thread can also own it until you give it up.

Of course, that does mean that they can't call any synchronized methods on objA (since that requires acquiring the lock), so if all of the modification methods on objA are synchronized (or use synchronized (this) {...} blocks), then the "no" becomes a "yes."

But if methodB never tries to lock on this (either by being synchronized, or by using a synchronized block), then no amount of locking on objA will block calls to objA.methodB().

yshavit
  • 42,327
  • 7
  • 87
  • 124
  • 1
    Note that a properly synchronized object also needs to synchronize the methods **reading** the state that is guarded by synchronized blocks. Only synchronizing the "modification methods" is not sufficient. – JB Nizet Sep 01 '17 at 07:37
  • @JBNizet Good point! The exception is if that state is in `volatile` fields -- but that's a more advanced topic. – yshavit Sep 01 '17 at 07:39
1

Synchronizing on a object locks the monitor of the object.
It means that no synchronized method or synchronized statement on an object can be executed if a thread is already executing in a synchronized statement (or a synchronized method) on this same object.

But things are different for no synchronized methods.
Indeed, any thread may invoke any no synchronized method on objA while a thread is executing in a synchronized statement on this same objA.

davidxxx
  • 125,838
  • 23
  • 214
  • 215