Reputation: 89
Suppose we have
class A {
synchronized void m1() {
}
synchronized void m2() {
}
void m3() {
}
static void m6() {
synchronized(this){
}
}
}
and two instances of class A a1&a2.
Now if thread t1 with instance a1 call the method m1,there is only restriction that thread t2 with instance a1 can't execute method m1 untill t1 finishes the execution of m1. And t2 with instance a2 can execute m1().
Now my doubt is Can thread t1 with a1 can execute other method's(except m1) parallaly while executing m1?
what's difference b/w synchronized block and synchronized method? Is the difference only that the block have lesser scope for synchronization so it is efficient?
I read an article stating "Synchronized block can throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null".
We always use "this" as parameter to synchronized block, so there is only and always case using synchronized block inside a static method.Beacuse we don't need an object instantian to execute static method.
Where did i misunderstood it?
Upvotes: 0
Views: 345
Reputation: 1
I think yes.
About synchronize on this ,-if you synchronize on 'this' or indeed any publicly visible object for the internal (or even external) logic of a particular class, you run the risk that something outside the class may "interfere" with things by holding on to the lock. So... whenever you are deciding on the locking mechanism for a particular case, you need to weigh things up and make it clear in your API what that object's locking policy is.
Upvotes: 0
Reputation: 1
for example, synchronized(this){...} will be run only around the actual critical section, and only on the current instance but synchronized(otherInstance){...} will works with other instance independently of current instance
Upvotes: 0
Reputation: 280167
Now if thread t1 with instance a1 call the method m1,there is only restriction that thread t2 with instance a1 can't execute method m1 untill t1 finishes the execution of m1. And t2 with instance a2 can execute m1().
This is correct. Since both threads are synchronized
on the same instance, the first Thread
gets to execute and the second Thread
gets to wait.
Now my doubt is Can thread t1 with a1 can execute other method's(except m1) parallaly while executing m1?
Yes, this is known as reentrant synchronization. Take a look at the end of this tutorial.
what's difference b/w synchronized block and synchronized method? Is the difference only that the block have lesser scope for synchronization so it is efficient?
A synchronized
block can be used on any instance. A synchronized
method synchronizes on this
implicitly. Try to use synchronized
blocks as often as possible only around the actual critical section.
I raed a article stating "Synchronized block can throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null".
The following
synchronized(null) {...}
would throw NullPointerException
.
Upvotes: 4