Path: csiph.com!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Jan Burse Newsgroups: comp.lang.java.programmer Subject: Re: synchronized methods "under the hood" Date: Wed, 06 Mar 2013 15:20:28 +0100 Organization: albasani.net Lines: 56 Message-ID: References: <7d23ce84-c209-43a2-bf88-2d112ce21a2e@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.albasani.net 02iR9lP6VhKfpxjpNQTUdxv9T+2G4EyJusQpAaRtA+cUIXidEZKMASixqFA1SJwzGKQ5Sc0qQdLez/T9odCSFg== NNTP-Posting-Date: Wed, 6 Mar 2013 14:20:28 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="UUaJJXJop3H3f9t+bcnlOEyBnRMA2PmkxDR/EaBQv5zSu4o3i/dJ4c3anf5RiHSuw5YzZjnk19Zmxb9+DOSapg1JfSMNqvmuUh8wPvFWlzoks83Q6d7q0hQvSO6JH3vR"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0 SeaMonkey/2.16 In-Reply-To: Cancel-Lock: sha1:kdNXQCW1nfaZbCwaZVEjyZh3/Ys= Xref: csiph.com comp.lang.java.programmer:22736 Roedy Green schrieb: > On Tue, 05 Mar 2013 23:44:34 +0100, Sven Köhler > wrote, quoted or indirectly quoted > someone who said : > >> 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 > > I thought he was asking about what happens at the hardware level. > Thread context switching I think is still done with software. > > Back in the 1990s I wrote a package in C to allow threads that ran on > a single CPU. Threads had to be well behaved and call "have a > conscience" periodically. It was remarkably simple, just save and > restore contexts. It is quite bit more complicated when you can > interrupt threads in mid instruction or when you have multiple CPUs. > You can google the OpenJDK source and find jvm_raw_lock etc.. in mutex.cpp. The Java locking uses a combination of atomic instructions for a fast path and subsequent parking of threads, which is I guess a queueing thing. Bottomline is that locking causes some overhead, seen for example when someone uses Vector instead of ArrayList. But the fast path makes it also not that expensive, so that a certain use of locking is tollerable. As an alternative one can sometimes use algorithms that use ordinary destructive instructions (i.e. object field write) in such a way, that reentrant operations result. Example from String: public int hashCode() { if (hash == 0) hash = .. compute hash .. return hash; } In the above it could happen that more than one thread computes the hash, if the check is interleaved by a context switch. But it doesn't do any harm, since String is immutable and always the same hash is calculated. Bye