The Artima Developer Community
Sponsored Link

Each thread has its own stack



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Each thread has its own stack

Posted by Bill Venners on 18 Oct 1998, 9:44 AM

> This is a snippet from the example of synchronizing by
> marking critical sections.

> public void setColor(int r, int g, int b) {
> checkRGBVals(r, g, b);
> synchronized (this) {
> this.r = r;
> this.g = g;
> this.b = b;
> }
> }
> private static void checkRGBVals(int r, int g, int b) {
> if (r < 0 || r > 255 || g < 0 || g > 255 ||
> b < 0 || b > 255) {
> throw new IllegalArgumentException();
> }
> }

> This method (setColor) requires reading of the r,g, and b
> instance variables to pass them to the class method checkRGBVals. But, unless I'm missing something (it's 4:00 on a Friday so that's possible), this method isn't synchronized with itself. If two threads called this at once, on could be reading the data to call checkRGBVals and one could be writing to it.

> right??

> shouldn't the call to checkRGBVals be inside the synchronize block too?

Well, no, because the values being passed to checkRGBVals are
being taken not from the instance variables r, g, and b, but
from the passed in parameters r, g, and b. The passed in
parameters are like local variables that sit on the stack,
and each thread has its own stack, so no two threads can
clobber each other over these values being passed to
checkRGBVals(). You only need to synchronize access to
the instance variables, which sit on the heap and can
be accessed by all threads.



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us