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


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

Re: a simple multi-thread question

From Robbie Brown <rob@example.com>
Newsgroups comp.lang.java.programmer
Subject Re: a simple multi-thread question
Date 2015-01-26 18:05 +0000
Organization A noiseless patient Spider
Message-ID <ma5vk9$vu7$1@dont-email.me> (permalink)
References <60c8877a-8321-4ba5-ab9a-8ccabd77874b@googlegroups.com> <ma5o15$s9p$1@dont-email.me>

Show all headers | View raw


On 26/01/15 15:55, Eric Sosman wrote:
> On 1/26/2015 10:40 AM, John wrote:
>>
>> I am amazed at what I saw:
>>
>> synchronized private void print()
>> {
>>       System.out.println("printing A");
>>       System.out.println("printing B");
>>       System.out.println("printing C");
>> }
>> [... he gets interleaved output ...]
>
>      Each Java object has its own lock ("monitor"), independent of the
> locks belonging to other Java objects.  When you call a synchronized
> instance method, Java acquires the lock of the "this" object before
> proceeding, and releases it when the method finishes.  If there are
> several object instances floating around, there are several "this"
> and several independent locks.
>
>> I thought the method is atomic.
>
>      No.  Synchronization is not about methods (or code blocks), but
> about objects: You lock the *object*, not a method.

Are you sure?

If you have a class with two methods and one (or more) of them is 
synchronized and one (or more) isn't then a thread can obtain the lock 
on an instance of that class which locks out all other threads from the 
synchronized methods but the non synchronized methods of that instance 
are still available to other threads.

At least that's how I remember it.

-- 
Not floundering ... just fishing

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


Thread

a simple multi-thread question John <xsli2@yahoo.com> - 2015-01-26 07:40 -0800
  Re: a simple multi-thread question Arne Vajhøj <arne@vajhoej.dk> - 2015-01-26 10:53 -0500
  Re: a simple multi-thread question Robert Klemme <shortcutter@googlemail.com> - 2015-01-26 07:54 -0800
  Re: a simple multi-thread question Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-01-26 10:55 -0500
    Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 18:05 +0000
      Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 18:08 +0000
        Re: a simple multi-thread question Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-01-26 17:19 -0500
      Re: a simple multi-thread question Arne Vajhøj <arne@vajhoej.dk> - 2015-01-26 13:27 -0500
        Re: a simple multi-thread question Robbie Brown <rob@example.com> - 2015-01-26 19:51 +0000
  Re: a simple multi-thread question Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> - 2015-01-28 21:55 +0200

csiph-web