Non-synchronised methods of an object in Java?

I need to clear a few basic concepts so as to check whether my understanding is correct or not.

1) Once a thread enters any synchronized method on an instance, no other thread can enter any other synchronized method on the same instance.

2) However, nonsynchronized methods on that instance will continue to be callable (by other threads). If yes, can I then say the whole object doesn't gets locked but only the critical methods which are synchronized.

3) Will I get the same behaviour as above for synchronized statement too:

synchronised(this){

     // statements to be synchronised  
}

or the whole object gets locked here with nonsynchronized methods on that instance not callable.

I think I am pretty confused with locking scope.

Upvotes: 2

Views: 103

Answers (4)

RohitS
RohitS

Reputation: 157

Your understanding is correct. All three statements you made, are valid. Please note one thing though, locks are not on methods(synchronized or non-synchronized). Lock is always on the object, and once one thread acquired the lock on an object, other threads have to wait till the lock is released and available for other threads to acquire.

Upvotes: 0

Y123
Y123

Reputation: 977

The code,

public synchronized void abc() {
...
}

it is conceptually same as,

public void abc() {
    synchronized(this) {
    }
}

In either of these cases the non-synchronized methods can be called when the monitor (in this case the object on which the method abc is called) is locked by a Thread executing a synchronized block or method.

Upvotes: 2

RealSkeptic
RealSkeptic

Reputation: 34618

Your statements are correct. Only synchronized code becomes protected. The object is simply used as the synchronizing lock, and it is not itself "locked".

And yes, you get the same behavior for synchronized blocks on the same object. In fact, you can synchronize blocks in the code of one object using another object as the lock.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182753

A lock only prevents other threads from acquiring that same lock -- the lock itself has no idea what it protects -- it's just something that only one thread can have. We say the whole object is locked because any other thread that attempts to lock the whole object will be unable to acquire that lock until it's released. Otherwise, your understanding is correct.

Upvotes: 3

Related Questions