Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!goblin2!goblin3!goblin.stu.neva.ru!odin.sdf-eu.org!.POSTED!not-for-mail From: dagon@dagon.net (Dagon) Newsgroups: comp.lang.java.programmer Subject: Re: A question about synchronized threads Date: Fri, 29 Apr 2011 15:55:34 -0700 Organization: Dagon.net Lines: 34 Message-ID: <68sr88-fuj.ln1@dagon.net> References: <3f249d87-aaf8-4732-9ee8-fd112cf82553@f31g2000pri.googlegroups.com> NNTP-Posting-Host: sverige.freeshell.org X-Trace: odin.sdf-eu.org 1304121341 26784 192.94.73.4 (29 Apr 2011 23:55:41 GMT) X-Complaints-To: usenet@odin.sdf-eu.org NNTP-Posting-Date: Fri, 29 Apr 2011 23:55:41 +0000 (UTC) mail-copies-to: never x-fastest-land-animal: cheetah disclaimer: bears author this post for full responsibility X-Newsreader: trn 4.0-test77 (Sep 1, 2010) Originator: dagon@dagon.net (Dagon) Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3367 byhesed 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(). Throw this book away and get a better one (Goetz, "Java Concurrency in Practict" is good). >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? This is kind of correct for this example, but it's stated in such a way that it will confuse you until you learn more completely what synchronized does. What it really does is: "before any thread enters m1 or m2, it will acquire an exclusive lock on the instance of A. No other thread may acquire that lock for that instance of A until the lock-holding thread releases it by exiting the method." >If it is correct, how can I handle it better? >I think it is too ineffectual. Does anybody know? Depends on what you want to happen - why do you think it's ineffectual? It's pretty effective if you want to make sure that only one thread at a time can run those methods on the same instance. -- Mark Rafn dagon@dagon.net