The Artima Developer Community
Sponsored Link




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.



Posted by Bill Venners on 18 Jul 1998, 8:55 AM

> I have enjoyed you Design Technique article ever since they
> appeared six months ago. This month's article just like the
> others explain the concept precisely and clearly in a manner
> that can be conceptualized by beginning or veteran programmers
> alike. Having said that I have one question regarding this month's
> article.

> Let say we chose to synchronize our accessor and modifier methods
> as follows (straightforward way):

> // synchronized modifier method
> public synchronized setColor (int R, int G, int B) {
> ...
> }

> // synchronized accessor method
> public synchronized int[] getColor () {
> ...
> }

> The blue thread steps through the setColor method is preempted
> to sleep before it finishes. The red thread then starts and tries
> to access the getColor method. Is it going to be blocked ? In
> other words, does putting the synchronize keyword at the method
> level automatically locks it from access by a second thread, once
> another synchronized method is in use and locked by another one ?

Yup, that's exactly what will happen. Anytime any thread enters
a critical section, that means the thread has "acquired the
monitor" associated with that critical section. If it is a
synchronized instance method, as in your example, that means
the thread must acquire the monitor of the object upon which
it has invoked the synchronized instance method. Once a thread
acquires a monitor, there are only a few ways it can release
the monitor:

1. Exit past the closing curly brace of the synchronized
block or return from the synchronized method
2. Exit the synchronized block or method abruptly with an
3. Execute a wait()

So in the case of your example, the blue thread acquires the
monitor by invoking setColor(), but gets preempted before
returning from setColor() (and assuming it doesn't complete
setColor() abruptly with an exception or invoke a wait()).
When the red thread invokes getColor(), it will be blocked.
(Red will be stuck into the object monitor's entry queue.
When the blue thread finally does release the monitor, the
red thread will compete for the monitor with any other
thread in the entry queue or wait set, i.e., with any other
thread that is interested in acquiring the monitor.) Only
when Red finally does get the monitor, will it start
executing getColor().



Sponsored Links

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