a few days ago i came across giant chen's article by the name of " when dtor meets mt".
that was a very good one, frankly. and i liked the way he presents it: very systematic, and most important of all understandable.
specifically he mentioned the following point there:
线程争用 (thread contention),即 Observable 的三个成员函数都用了互斥器来同步,这会造成 register 和 unregister 等待 notifyObservers,而后者的执行时间是无上限的,因为它同步回调了用户提供的 update() 函数。我们希望 register 和 unregister 的执行时间不会超过某个固定的上限,以免即便殃及无辜群众。
that's pretty much true, but here i just want to talk a bit more on how to do update() maybe in a more appropriate way because some words right there actually reminded me of some interview question i personally ran up against sometime back: how to decouple classes.
so the question is, the Observable calls the update() method of each Observer, the performance of the Observable could be tied to the performance of the update() methods in each Observer. and, at this stage of me (i mean after working for more than 1 decade), to minimize the performance impact on the Observable, decouple the Observers from the Observable using a threaded queue (FIFO) or even a priority queue should there be such a requirement for such priority calls. The threaded queue is inserted between the Observable and its Observers. The threaded queue becomes the single Observer to the Observable, and all the real Observers become Observers of the threaded queue.
with Java, it's really convenient to do so: (sorry it's not intended to be runnable)
public class
ObserverQueue extends Observable implements Observer, Runnable
{
ObserverQueue() {}
public void run() {
while( true ) {
msg = get();
setChanged();
notifyObservers( msg );
}
}
public void update( Observable obj, Object arg) {
put( arg );
}
}
here get() is a blocking call in my opinion, for the purpose of this article. ( i know gchen is object to any concept of blocking :) )
i just regret that i didn't ask the interviews what they meant when they say "decoupling of classes"? decoupling in terms of running or just structural ones? your thoughts?
finally and furthermore, just fyi, if the update() method invokes other methods, each of those methods is executed on the Observable's stack - which could cause the program to crash sometime - i've seen this once even in a ET Production component. so a programmer, esp. when you work on lib/components that would call users' code, first rule is to be as much cautious as possible - never make any assumption about what the users will do - they will do any bad things you could think of, to you, towards you :) and they tend to deny this by mentioning of the ignorance of your stuff. that's really bad. pretty much bad.
i hate that and i hope everybody could just be like gchen :)
posted on 2011-08-30 07:34
w2j3s8 阅读(82)
评论(0) 编辑 收藏 引用