Kraken
Kraken

Reputation: 24243

Class with all methods synchronised will behave as a synchronised block?

public class SynchronizedCounter {
private int c = 0;

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

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

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

If there are two threads, each having the same instance of SynchronizedCounter, does this mean that if one thread is calling increment, the other can not call decrement. Is the above code equivalent to a synchronised object? i.e.

public void run(){
    synchronised( objectReferenceSynchronisedCounter){
        if(conditionToIncrement)
        objectReference....Counter.increment();
        else
        objectReference....Counter.decrement();
    }
}

Upvotes: 0

Views: 72

Answers (3)

Florian F
Florian F

Reputation: 1377

There are 2 questions:

If there are two threads, each having the same instance of SynchronizedCounter, does this mean that if one thread is calling increment, the other can not call decrement.

That is correct. The call to decrement will be blocked while the other thread executes increment. And vice-versa.

Is the above code equivalent to a synchronised object? [code follows]

Your second example is slightly different because you include an if statement in the synchronized block. And generally speaking if a synchronization bloc includes multiple calls, it is not equivalent to synchronizing each individual call.

There is no such thing as a synchronized object in Java. You synchronize methods or code blocks.

However, and maybe that is what you meant, in both your examples the lock is held on the same object, namely the instance of the object whose methods are called. So apart from the slightly different scope, the 2 examples synchronize in the same way on the same object.

Upvotes: 1

BillFromHawaii
BillFromHawaii

Reputation: 334

It is exactly a synchronized object. "synchronized" on the method locks "this" once one of your methods is called the others cannot execute until the method id exited.

Upvotes: 0

Gab
Gab

Reputation: 8332

The answer is no.

the synchronized scope is the modified method

See http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html

Upvotes: 1

Related Questions