Synchronized Observable List
alspaughb at gmail.com
Sat Sep 22 14:58:49 PDT 2012
I'm new to JavaFX, so I was browsing the Javadoc for:
It doesn't say whether it synchronizes on the returned list or some
other object that might not be accessible to me. Can I safely assume it
synchronizes on the intrinsic lock of the wrapper?
A potential problem with observable synchronized collections is that you
have to be very careful not to call an "alien" method while holding a
lock which risks deadlock and other synchronization problems as
described in Item 67 of Effective Java. In this case, the listeners
registered on the wrapper would be considered "alien" to JavaFX. If the
wrapper naively holds the lock while forwarding the call to the
corresponding method of the wrapped list, the lock would be held during
the time the listeners are being notified, risking exceptions and
One approach to work around this issue would be to use a condition
variable on the lock to temporarily suspend it while the registered
listeners are notified, and then regain it after the listeners have been
notified. This would require some sophistication and overhead to the
underlying code that notifies listeners in JavaFX.
I have concerns about the approach of moving the listener notifications
outside the critical section and the CopyOnWriteArrayList approach as
described in Effective Java Item 67, because you can't guarantee the
order that listeners are notified when multiple threads concurrently
modify the collection, and the listeners themselves would have to be
able to handle concurrent notification. For example, if thread 1 makes
change A and thread 2 makes change B to the same collection, you can't
guarantee that a listener would be notified of A before B, B before A,
or it could be concurrently notified of A and B. I also don't see how
Dr. Bloch is guarding the backing Set from concurrent modification. I
understand it could be a thread-safe Set, like CopyOnWriteArraySet, but
there is nothing to guarantee it is so.
I suppose the simplest approach of all would be to simply confine
observable collections to a single thread. What is the use case that
requires an observable collection to be concurrently modified? Could
the use case be handled some other way?
If someone could point me to where I can browse the JavaFX source code
so I can see what is actually going on here, it would be quite helpful.
More information about the openjfx-dev