Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!us.feeder.erje.net!feeder.erje.net!eu.feeder.erje.net!news-1.dfn.de!news.dfn.de!fu-berlin.de!uni-berlin.de!news.dfncis.de!not-for-mail From: =?ISO-8859-1?Q?Sven_K=F6hler?= Newsgroups: comp.lang.java.programmer Subject: Re: synchronized methods "under the hood" Date: Tue, 05 Mar 2013 23:44:34 +0100 Lines: 28 Message-ID: References: <7d23ce84-c209-43a2-bf88-2d112ce21a2e@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: news.dfncis.de +1ytpyjrYH80WswlSo0f8gYaU2hQ+P6qnLGHit/BAQRr7ufmPYw6ytrOvZLdzv4EZciLxQy16i Cancel-Lock: sha1:HFsXcT2QvL30MfL3pbivWj+RJv0= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130223 Thunderbird/17.0.3 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:22733 Am 05.03.2013 21:19, schrieb Roedy Green: > On Tue, 5 Mar 2013 09:02:25 -0800 (PST), bob smith > wrote, quoted or indirectly quoted someone > who said : > >> How do synchronized methods work "under the hood"? >> >> Is there some kind of byte associated with each object that acts as a semaphore? > > At the hardware level these are usually handled by some sort of test > and test instruction. It tests if a byte is zero, and if it is, sets > it to 1. It locks out any other CPU or thread from interfering > between the test and set. If reports if the byte was zero to start > (in other words we successfully locked.) Test and Set is an "atomic" > operation. Such test and set methods are implemented in Java's Atomic* classes (e.g. AtomicInteger). However, you need more than that to implement a proper mutex. What I would call a proper mutex puts a thread to sleep, if it cannot lock the mutex. To do that, you need to tell the kernel that the thread is suspended. As far as I know, Linux futexes do both: they first check whether the mutex is locked by using some atomic test+set, and if that fails they resort to syscalls: http://en.wikipedia.org/wiki/Futex Regards, Sven