mino
mino

Reputation: 7288

Java Monitors - Do synchronised methods prevent any other thread being IN that object?

Does the following mean that only ONE thread can be in ANY method of the object? Or can a multiple threads be in DIFFERENT methods just not the same one? Why?

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

Upvotes: 2

Views: 125

Answers (3)

fastcodejava
fastcodejava

Reputation: 41117

Of course, they are synchronized on the this object. If you had written your own synchronized block with different objects for the different methods you have then it won't be the case.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359966

Does the following mean that only ONE thread can be in ANY method of the object?

Yes. Non-static synchronized methods implicitly synchronize on this. It's equivalent to:

public void increment() {
    synchronized(this) {
        c++;
    }
}

If this were a real piece of code (I know it's not), I would recommend throwing out your SynchronizedCounter class entirely and using AtomicInteger instead.

Upvotes: 2

Don Roby
Don Roby

Reputation: 41135

Does the following mean that only ONE thread can be in ANY method of the object?

For your specific example, yes, because all the methods are synchronized and non-static.

If your class had any unsynchronized methods, then the unsynchronized methods would not be blocked.

If your class used synchronized blocks instead of methods and synchronized them on different locks, it could get much more complex.

Upvotes: 2

Related Questions