Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #22733

Re: synchronized methods "under the hood"

From Sven Köhler <remove-sven.koehler@gmail.com>
Newsgroups comp.lang.java.programmer
Subject Re: synchronized methods "under the hood"
Date 2013-03-05 23:44 +0100
Message-ID <apnan8FdajU1@mid.dfncis.de> (permalink)
References <7d23ce84-c209-43a2-bf88-2d112ce21a2e@googlegroups.com> <fpkcj8l7bqvg5qoki7m0b4dom3ha0qfp0f@4ax.com>

Show all headers | View raw


Am 05.03.2013 21:19, schrieb Roedy Green:
> On Tue, 5 Mar 2013 09:02:25 -0800 (PST), bob smith
> <bob@coolfone.comze.com> 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

Back to comp.lang.java.programmer | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

synchronized methods "under the hood" bob smith <bob@coolfone.comze.com> - 2013-03-05 09:02 -0800
  Re: synchronized methods "under the hood" Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-03-05 09:15 -0800
  Re: synchronized methods "under the hood" Jan Burse <janburse@fastmail.fm> - 2013-03-05 18:59 +0100
    Re: synchronized methods "under the hood" Jan Burse <janburse@fastmail.fm> - 2013-03-05 19:16 +0100
    Re: synchronized methods "under the hood" Jan Burse <janburse@fastmail.fm> - 2013-03-06 15:24 +0100
  Re: synchronized methods "under the hood" Roedy Green <see_website@mindprod.com.invalid> - 2013-03-05 12:19 -0800
    Re: synchronized methods "under the hood" Sven Köhler <remove-sven.koehler@gmail.com> - 2013-03-05 23:44 +0100
      Re: synchronized methods "under the hood" Roedy Green <see_website@mindprod.com.invalid> - 2013-03-06 04:28 -0800
        Re: synchronized methods "under the hood" Jan Burse <janburse@fastmail.fm> - 2013-03-06 15:20 +0100

csiph-web