Re: synchronized methods "under the hood"
Roedy Green schrieb:
On Tue, 05 Mar 2013 23:44:34 +0100, Sven K?hler
<remove-sven.koehler@gmail.com> 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