>Firstly, it looks to me like your code would hang in a deadlock. Take
>for
>example..
>
>Thread1Thread2
>enter beginReading()
>exit beginReading()
>doing some reading enter beginWriting() [and blocking]
>now can't call endReading()
>
>Now it looks like to me, that this is a deadlock. Thread2 is
>syncronized on the object and waiting for notification. Unfortunately
Thread1 now
>cannot enter endReading as Thread2 is holding the sync lock on the object.
The situation you describe does not cause deadlock because the wait()
call in thread
2 releases the synchronized lock. Basically, Java synchronization is
built around
the idea of a "monitor" with wait() and notify() methods (reference your
favorite
OS book). Unfortunately, Java does
not allow the use of signaling multiple conditions on a wait (without
some ugly hacks).
I suppose they designed Java this way because with monitors it is easier
to prove code
correct than it is with semaphores or other primitives.
>The second issue is that looks to me as if (in the case of the
>ReadersPreferred) that if there are enough threads trying to read and
>the
>read takes a reasonable amount of time, then writers could block
>indefinately.
This is correct. Perhaps the class should be called
WritersStarvationMonitor. One could use
an alternating scheme (between batches of readers and a single writer)
as you describe.
>But what we do have now are two syncronized methods to get and release
>access for a read - and as the read should be very fast, this may have
>a
>negative impact on the throughput of multi-threaded reads. Syncronized
>calls
>have a large performance impact - as does try/catch/finally which you
>will
>now have to put around your reading routines
The only way I can think of to alleviate this problem is use different
synchronization primitives. Unfortunately, Java
doesn't have them. And all libraries that simulate these use
synchronization!
Now, maybe someone here could hack some byte code
(does Java have a set-and-test instruction??) and
produce them... ;-)
Regards,
Matt