We help IT Professionals succeed at work.

Syncronize blocks & synchronized methods

modsiw
modsiw asked
on
Suppose I have a class, Foo, that has synchronized methods (ie: public void synchronized bar() {} )

Suppose I have a second class that instantiates Foo as myFoo.

Will a synchronized block on myFoo also prevent calls from other threads to the bar method of myFoo until completes?

There is an example situation below using a map.
final Map m = Collections.synchronizedMap(new HashMap());

void switchIfNotEmpty(Object k, Object v)
{
  synchronized(m) {
    if (m.containsKey(k)) m.put(k,v);
  }
}

Open in new window

Comment
Watch Question

Top Expert 2016
Commented:
>>Will a synchronized block on myFoo also prevent calls from other threads to the bar method of myFoo until completes?

Yes. The lock is on the whole object

Author

Commented:
Is there any difference between:

public void synchronized bar() { /* stuff */ }

and

public void bar()
{
  synchronized (this) { /* stuff */ }
}

Author

Commented:
Top Expert 2016

Commented:
:-)