lboyel
lboyel

Reputation: 2218

Synchronze on method call Java

I have a question about a block of code I am trying to understand

synchronized(Name.getname())
{
   Name.getname().add(this);
}

What does this block of code synchronize on? does it synchronize on the method call result or something else.

Upvotes: 0

Views: 79

Answers (4)

Solomon Slow
Solomon Slow

Reputation: 27115

I'm not adding any information that you can't find in the other answers, but sometimes a picture helps.

I'm guessing that Name.getName() returns a reference to a singleton Name instance. If that's true, then your example is equivalent to this:

Name n = Name.getName();
synchronized(n) {
    n.add(this);
}

It seems strange to me that something called "Name" would be a singleton, and it seems strange to me that you would be allowed to add this to something called "Name", but I can't make any sense of your example at all unless Name.getName() always returns the same object reference.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

It synchronizes on the object returned by Name.getname().

Just like System.out.println(Name.getname()) prints the value returned by Name.getname().

Everywhere you use an Object, an expression of type Object can be used.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201409

The (reference) value that is returned by getname() in the Name instance (or the static method if it isn't an instance) is used as the lock object.

Upvotes: 1

Gurkan İlleez
Gurkan İlleez

Reputation: 1573

Yes it is synchronized. You used Name.getname() as a lock object. If one thread acquires the Name.getname() object then other thread will wait until releasing object

Upvotes: 4

Related Questions