Java Forum / General / November 2005
Question about synchronized
Matthias Kaeppler - 12 Nov 2005 13:26 GMT Hi,
say I have two different methods M1 and M2 which work on the same object O, whereas M1 is declared 'synchronized' while M2 is not. Now imagine I start two threads A and B, which keep calling M1 and M2 respectively in an endless loop.
As far as I can tell, if M1 is called by A, a lock is acquired on O and thus each call to M2 in B's context will result in the VM inserting B in the wait set until M1 has finished (this is only because M1 is synchronized).
But what if M2 is called on O in B's context /first/ (remember it's not synchronized), and no lock is acquired on O, and while it's still computing, the VM decides to give A the CPU? Will M1 now be able to work on O, even though M2 hasn't finished yet?
In other words, is in my case of two functions, two threads and one object the program only thread safe if /both/ methods M1 and M2 are declared synchronized? And what effects could arise from one being not not while the other is?
Thanks, Matthias
VisionSet - 12 Nov 2005 14:06 GMT > Hi, > [quoted text clipped - 7 lines] > the wait set until M1 has finished (this is only because M1 is > synchronized). No M1 is not sync'd and can be called at any time, by any thread.
> But what if M2 is called on O in B's context /first/ (remember it's not > synchronized), and no lock is acquired on O, and while it's still > computing, the VM decides to give A the CPU? > Will M1 now be able to work on O, even though M2 hasn't finished yet? Yes, because no lock was ever obtained until M1 was called.
> In other words, is in my case of two functions, two threads and one > object the program only thread safe if /both/ methods M1 and M2 are > declared synchronized? And what effects could arise from one being not > not while the other is? As above!
-- Mike W
Matthias Kaeppler - 12 Nov 2005 14:25 GMT >>say I have two different methods M1 and M2 which work on the same object >>O, whereas M1 is declared 'synchronized' while M2 is not. [quoted text clipped - 7 lines] > > No M1 is not sync'd and can be called at any time, by any thread. M1 /is/ synced, I suppose you mean M2?
>>But what if M2 is called on O in B's context /first/ (remember it's not >>synchronized), and no lock is acquired on O, and while it's still [quoted text clipped - 9 lines] > > As above! Okay, thanks.
- Matthias
VisionSet - 12 Nov 2005 14:30 GMT > > No M1 is not sync'd and can be called at any time, by any thread. > > M1 /is/ synced, I suppose you mean M2? err, yes
Roedy Green - 12 Nov 2005 14:18 GMT >methods M1 and M2 Classes start with a upper case letter and methods with a lower case one.
You have no idea how strange code that violates the Sun convention is to people who rigidly follow it.
It is like saying a man named Barbi and a woman named Tex decided to get married. They hired a preacher named Bowser. Their pet dog was named Sheldon. The best Man's name was Cauliflower with cheese and the bridemaid was Duck a Limon.
What colour tux should Sheldon wear?
see http://mindprod.com/jgloss/codingconventions.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Matthias Kaeppler - 12 Nov 2005 14:24 GMT >>methods M1 and M2 > [quoted text clipped - 12 lines] > > see http://mindprod.com/jgloss/codingconventions.html You obviously completely missed my point, did you even read my post beyond that line? ^^ I was obviously referring to an artificial setup which ought to represent my problem. We call that abstraction.
Regards, Matthias
VisionSet - 12 Nov 2005 14:28 GMT > You obviously completely missed my point, did you even read my post > beyond that line? ^^ > I was obviously referring to an artificial setup which ought to > represent my problem. We call that abstraction. To be fair, Roedy has a good point. When you stare at code all day, you just don't see entities starting with a capital as an Object. I only let it slip because you hadn't actually written any code, but I keep to the conventions in pros, because it means Java folk will get the meaning more quickly. -- Mike W
Matthias Kaeppler - 12 Nov 2005 14:38 GMT > To be fair, Roedy has a good point. > When you stare at code all day, you just don't see entities starting with a > capital as an Object. > I only let it slip because you hadn't actually written any code, but I keep > to the conventions in pros, because it means Java folk will get the meaning > more quickly. Heh, okay, I didn't expect anyone to be overstrained by referring to a method in uppercase... I'll keep it in mind :)
Roedy Green - 12 Nov 2005 15:20 GMT >Heh, okay, I didn't expect anyone to be overstrained by referring to a >method in uppercase... I'll keep it in mind :) People who persist in doing it are usually snotty brat know-it-alls who do it just to annoy the very people they are supposedly asking to help them. I doubt that was your intention.
.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Thomas G. Marshall - 13 Nov 2005 04:03 GMT Roedy Green coughed up:
>> Heh, okay, I didn't expect anyone to be overstrained by referring to a >> method in uppercase... I'll keep it in mind :) > > People who persist in doing it are usually snotty brat know-it-alls > who do it just to annoy the very people they are supposedly asking to > help them. I doubt that was your intention. I'm not sure I see what he did as any different than saying
If person X makes Y amount of money....
He abstracted out the M1 not as the /identifier/ but the abstracted name for it. Meta meta meta meta meta....I just don't see an issue with it.
 Signature Doesn't /anyone/ know where I can find a credit card company that emails me the minute something is charged to my account?
Roedy Green - 12 Nov 2005 15:18 GMT >You obviously completely missed my point, did you even read my post >beyond that line? ^^ no, and I thought you should know why you are not getting as many responses as you expected.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Matthias Kaeppler - 12 Nov 2005 15:40 GMT >>You obviously completely missed my point, did you even read my post >>beyond that line? ^^ > > no, and I thought you should know why you are not getting as many > responses as you expected. Are you trying to tell me that I received less responses than other people because I used uppercase notation for a method? I hope you know how ridiculous that sounds. But anyway, I already told you, next time I will remember that and use camel-case all the way to make you smile again! :D
No seriously, I actually had no expectations at all about the quantity of responses since I rarely post here (I just don't use it as frequent as, say, C++), but I am happy with all responses so far (and already said so).
Best regards, Matthias
Roedy Green - 13 Nov 2005 02:58 GMT >Are you trying to tell me that I received less responses than other >people because I used uppercase notation for a method? YES!
You piss people off when you do that.
It is like top posting.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 13 Nov 2005 03:00 GMT >Are you trying to tell me that I received less responses than other >people because I used uppercase notation for a method? I hope you know >how ridiculous that sounds. Obviously, you got at least one less than expected because I refused to answer your questions, and I usually answer posts..
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
John C. Bollinger - 13 Nov 2005 03:14 GMT >>> You obviously completely missed my point, did you even read my post >>> beyond that line? ^^ [quoted text clipped - 5 lines] > people because I used uppercase notation for a method? I hope you know > how ridiculous that sounds. I hope you will grasp that no matter how ridiculous Roedy's assertion may sound to you, it is quite possibly true. Many newsgroup participants (in any group) are restrictive about which posts they read, and most are even more restrictive about which they respond to. Myself, I doubt whether I read 25% of the posts to this group. If a post is hard to read -- for whatever reason -- then it is likely that considerably fewer people will bother with it than otherwise would do.
Also, taking the attitude that your post *deserves* attention, or any particular kind of response, does not resonate well on Usenet. If I had seen the exchange between you and Roedy before posting my response to your original message then I might not have bothered.
 Signature John Bollinger jobollin@indiana.edu
Steve Horsley - 12 Nov 2005 14:29 GMT > Hi, > [quoted text clipped - 7 lines] > the wait set until M1 has finished (this is only because M1 is > synchronized). No, this is wrong. When B calls M2, it does not try to acquire the lock, and therefore does not discover that it is already locked by A. B (also C, D and E at the same time) is free to enter M2 regardless of whether anyone has the lock.
> But what if M2 is called on O in B's context /first/ (remember it's not > synchronized), and no lock is acquired on O, and while it's still > computing, the VM decides to give A the CPU? > Will M1 now be able to work on O, even though M2 hasn't finished yet? Yes. Although no other threads will be able to enter M1 until A leaves it.
> In other words, is in my case of two functions, two threads and one > object the program only thread safe if /both/ methods M1 and M2 are > declared synchronized? And what effects could arise from one being not > not while the other is? That's right.
Steve
Matthias Kaeppler - 12 Nov 2005 14:34 GMT >> As far as I can tell, if M1 is called by A, a lock is acquired on O >> and thus each call to M2 in B's context will result in the VM [quoted text clipped - 5 lines] > C, D and E at the same time) is free to enter M2 regardless of whether > anyone has the lock. That's interesting. Doesn't that effectively render my synchronized function useless in terms of atomicity, when anyone can go ahead and call his/her unsynced methods on my object, even if I own that lock? ^^
Regards, Matthias
Thomas G. Marshall - 13 Nov 2005 04:11 GMT Matthias Kaeppler coughed up:
>>> As far as I can tell, if M1 is called by A, a lock is acquired on O >>> and thus each call to M2 in B's context will result in the VM [quoted text clipped - 9 lines] > function useless in terms of atomicity, when anyone can go ahead and > call his/her unsynced methods on my object, even if I own that lock? ^^ There is no lock honored unless all the participants that are intended to be locked out from each other are engaging in synchronization.
If you have
public class Hooey { public synchronized void m1() {...} public synchronized void m2() {...} public synchronized void m3() {...} public void m4() {....} }
then m4() is free to be called and executed without regard to the mutex. That means it can do anything to the object. The full explanations of how this all works is beyond the scope of a usenet post.
 Signature Doesn't /anyone/ know where I can find a credit card company that emails me the minute something is charged to my account?
John C. Bollinger - 12 Nov 2005 14:32 GMT > say I have two different methods M1 and M2 which work on the same object > O, whereas M1 is declared 'synchronized' while M2 is not. > Now imagine I start two threads A and B, which keep calling M1 and M2 > respectively in an endless loop. So thread A only calls M1, and thread B only calls M2? OK.
> As far as I can tell, if M1 is called by A, a lock is acquired on O and > thus each call to M2 in B's context will result in the VM inserting B in > the wait set until M1 has finished (this is only because M1 is > synchronized). No, that's not entirely correct. Thread A does lock O's monitor once at each entry to M1, and it unlocks the monitor once at each exit from M1, but that has no effect on any thread invoking /unsynchronized/ method M2.
> But what if M2 is called on O in B's context /first/ (remember it's not > synchronized), and no lock is acquired on O, and while it's still > computing, the VM decides to give A the CPU? > Will M1 now be able to work on O, even though M2 hasn't finished yet? Yes. You should think of synchronization as protecting sections of code -- either blocks or methods -- not objects. It is in fact mostly a convenience that every object /has/ a monitor at all; the object whose monitor you use to synchronize a particular block of code does not have to have any particular relation to the class that owns the code. Synchronized methods automatically synchronize on the object they are invoked on, but with a synchronized block you specify which object's monitor is used. This is very important.
> In other words, is in my case of two functions, two threads and one > object the program only thread safe if /both/ methods M1 and M2 are > declared synchronized? And what effects could arise from one being not > not while the other is? If both M1 and M2 are synchronized then no more than one thread will ever execute in either one of them (collectively) at any particular time. This may be sufficient for thread safety, but it is not certain to be sufficient. The canonical example here is the Collections classes: suppose I have a Collection whose methods are all synchronized. Thread T1 gets the Collection's iterator and starts iterating through the elements. Meanwhile, thread T2 adds an element to the Collection in between T1's invocations of next(). The synchronization ensures that the Collection's internal state remains consistent and means that there is no data race in the sense that that term is used in the latest Java language spec. The synchronization of the individual methods does not prevent T1 from receiving a ConcurrentModificationException. The solution in this case is to put the whole iteration inside a block synchronized on the Collection.
To get a grip on multithreaded programming in Java it is also important to understand the use and effects of Object.wait(), .notify(), and .notifyAll(), and to appreciate the nondeterminism of the thread scheduler. Those are topics for another post, however.
 Signature John Bollinger jobollin@indiana.edu
Matthias Kaeppler - 12 Nov 2005 14:53 GMT >> As far as I can tell, if M1 is called by A, a lock is acquired on O >> and thus each call to M2 in B's context will result in the VM [quoted text clipped - 4 lines] > each entry to M1, and it unlocks the monitor once at each exit from M1, > but that has no effect on any thread invoking /unsynchronized/ method M2. I see.
>> But what if M2 is called on O in B's context /first/ (remember it's >> not synchronized), and no lock is acquired on O, and while it's still [quoted text clipped - 9 lines] > invoked on, but with a synchronized block you specify which object's > monitor is used. This is very important. Yes, I was aware of the difference between synchronized being used as a statement as opposed to being used as a modifier for methods, but I wasn't sure about the mechanics between sychronized blocks of code (or methods) and such that aren't synchronized.
>> In other words, is in my case of two functions, two threads and one >> object the program only thread safe if /both/ methods M1 and M2 are [quoted text clipped - 20 lines] > .notifyAll(), and to appreciate the nondeterminism of the thread > scheduler. Those are topics for another post, however. That was quite insightful, thanks.
Regards, Matthias
Thomas G. Marshall - 13 Nov 2005 04:27 GMT John C. Bollinger coughed up:
...[rip]...
> Yes. You should think of synchronization as protecting sections of code > -- either blocks or methods -- not objects. Yes! And where were you when I was getting railed on for making such a claim in september '04?
;)
...[rip]...
 Signature Doesn't /anyone/ know where I can find a credit card company that emails me the minute something is charged to my account?
Chris Uppal - 13 Nov 2005 11:50 GMT > > Yes. You should think of synchronization as protecting sections of code > > -- either blocks or methods -- not objects. > > Yes! And where were you when I was getting railed on for making such a > claim in september '04? I also wondered if "John" is being spoofed, or possibly has been taken over by mind-eating aliens ;-)
For the record: /I/ am still me, and so am unchanged in my opinion that talking of "protecting sections of code" is badly misleading...
-- chris
Thomas G. Marshall - 13 Nov 2005 14:45 GMT Chris Uppal coughed up:
>>> Yes. You should think of synchronization as protecting sections of code >>> -- either blocks or methods -- not objects. [quoted text clipped - 10 lines] > > -- chris {Grumble}. Stepping back and squinting, it all comes down to how far up or down the abstraction ladder you want to go I suppose. "it's a car!" "it's a pile of atoms" "what's the point in the atoms if it doesn't form the car?" "how can you possibly have a car without the atoms?" (pun on atomic not intended).
 Signature Having a dog that is a purebred does not qualify it for breeding. Dogs need to have several generations of clearances for various illnesses before being bred. If you are breeding dogs without taking care as to the genetic quality of the dog (again, being purebred is *not* enough), you are what is known as a "backyard breeder" and are part of the problem. Most of the congenital problems of present day dogs are traceable directly to backyard breeding. Spay or neuter your pet responsibly, and don't just think that you're somehow the exception and can breed a dog without taking the care described.
John C. Bollinger - 14 Nov 2005 06:32 GMT >>>Yes. You should think of synchronization as protecting sections of code >>>-- either blocks or methods -- not objects. [quoted text clipped - 4 lines] > I also wondered if "John" is being spoofed, or possibly has been taken over by > mind-eating aliens ;-) If I deny it will you believe me? :-)
> For the record: /I/ am still me, and so am unchanged in my opinion that talking > of "protecting sections of code" is badly misleading... It looks like I really stepped in it. I think, however, that this debate is more about terminology and personal mental models than it is about conflicting understanding among us (Chris, Thomas, and me) of how synchronization affects program behavior. The OP was clearly confused about the implications of objects having associated monitors, and at this point I predict that he will indeed have more success in understanding the behavior of multithreaded programs if he focuses his attention on which sections of his code need to be synchronized, on which monitor. I think in any case that he has taken the point, which is that locking an object's monitor does not prevent access to any unsynchronized part of any object's behavior.
 Signature John Bollinger jobollin@indiana.edu
Chris Uppal - 14 Nov 2005 12:15 GMT > It looks like I really stepped in it. I think, however, that this > debate is more about terminology and personal mental models than it is > about conflicting understanding among us (Chris, Thomas, and me) of how > synchronization affects program behavior. And also about what we feel can safely be left unsaid in a high-level description. My object-centric viewpoint won't let me leave them out. (Not trying to re-open the debate, just giving an example of what I mean).
-- chris
Thomas G. Marshall - 14 Nov 2005 14:12 GMT Chris Uppal coughed up:
>> It looks like I really stepped in it. I think, however, that this >> debate is more about terminology and personal mental models than it is [quoted text clipped - 5 lines] > (Not > trying to re-open the debate, just giving an example of what I mean). This has been fairly clear from you, and from Lee (to a huge extent :) ) as well. Speaking as an off and on instructor, however, I've seen the higher levels of object state and monitors slow down entirely the learning of what's actually taking place. And this confusion will often last clear into "senior engineer" land. Engineers will often just view synchronization as some snake-oil magic. We've all seen this belief in synchronized magic bullets. IMO, the way to solve this is to have the person focus on the notion of /critical section/ first, and how the mutex works.
I've actually seen people suggest adding synchronization even when there is no multithreading going on at all! I believe John C. Bollinger is right in his assessment in this case as well: the OP needs to understand the [slightly] lower level of what's going on, which he clearly doesn't.
 Signature Unix users who vehemently argue that the "ln" command has its arguments reversed do not understand much about the design of the utilities. "ln arg1 arg2" sets the arguments in the same order as "mv arg1 arg2". Existing file argument to non-existing argument. And in fact, mv itself is implemented as a link followed by an unlink.
John C. Bollinger - 14 Nov 2005 06:16 GMT > John C. Bollinger coughed up: > [quoted text clipped - 7 lines] > > ;) At lunch? The dentist's? Pining for the fjords? :-)
 Signature John Bollinger jobollin@indiana.edu
Thomas G. Marshall - 14 Nov 2005 14:21 GMT John C. Bollinger coughed up:
>> John C. Bollinger coughed up: >> [quoted text clipped - 9 lines] > > At lunch? The dentist's? Pining for the fjords? :-) Yeah, well, that's ok. There were well over 1300 posts in that thread, and we wondered all over up down left and right. I shouldn't have contributed here, but it may be too late.
Into the abyss......... ;)
 Signature Unix users who vehemently argue that the "ln" command has its arguments reversed do not understand much about the design of the utilities. "ln arg1 arg2" sets the arguments in the same order as "mv arg1 arg2". Existing file argument to non-existing argument. And in fact, mv itself is implemented as a link followed by an unlink.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|