On 4=BF=F930=C0=CF, =BF=C0=C0=FC12=BD=C358=BA=D0, Daniele Futtorovic <da.fu=
On 29/04/2011 17:35, byhesed allegedly wrote:
public class A {
synchronized void m1() { ... }
synchronized void m2() { ... }
void m3() { ... }
}
The book explains above code:
Given an instance a of class A, when one thread is executing
a.m1(),
another thread will be prohibited from executing a.m1() or a.m2().
I have a question.
The explanation means than when one thread is executing m1() method,
No other threads can execute m1() or m2() thread.
Is it correct?
Yes, it is correct.
If it is correct, how can I handle it better?
I think it is too ineffectual. Does anybody know?
By defining yourself the monitor you synchronise on.
When you declare a method synchronized, the code will use the instance
of which that method is a member as the monitor. In other words, the
code above is equivalent to this:
public class A {
void m1() {
synchronized( this ){ ... }
}
void m2() {
synchronized( this ){ ... }
}
void m3() { ... }
}
Both method lock on the same monitor, so when one is executed, no other
thread can execute any of them.
If you don't want that interdependency, you can define monitors yourself:
public class A {
private final Object
m1Monitor = new Object(),
m2Monitor = new Object()
;
void m1() {
synchronized( m1Monitor ){ ... }
}
void m2() {
synchronized( m2Monitor ){ ... }
}
void m3() { ... }
}
That way, a thread executing m1 will not prevent another thread from
executing m2, only m1 itself.
--
DF.
An escaped convict once said to me:
"Alcatraz is the place to be"
Thank you. I understand what you elaborated on.