Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Daniele Futtorovic Newsgroups: comp.lang.java.programmer Subject: Re: A question about synchronized threads Date: Fri, 29 Apr 2011 17:58:40 +0200 Organization: A noiseless patient Spider Lines: 67 Message-ID: References: <3f249d87-aaf8-4732-9ee8-fd112cf82553@f31g2000pri.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Fri, 29 Apr 2011 15:58:41 +0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="HVQCu0Y2HgWFwFmevj7r/w"; logging-data="13913"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/FVKy0hJV9kGh6Wjq/SivG" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.15) Gecko/20110303 Thunderbird/3.1.9 In-Reply-To: <3f249d87-aaf8-4732-9ee8-fd112cf82553@f31g2000pri.googlegroups.com> Cancel-Lock: sha1:G8cIYlzG51vVN+a3LC7NGFQjZAY= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3356 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"