Question

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;
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top