您的位置:首页 > 编程语言 > Java开发

API考古学之“C风格的Java API”

2007-12-26 19:05 429 查看
By pongba
 
 
#从fishbowl上看到的,非常幽默:
Occasionally in Java, you come across an API that makes you sit up and go “What were they thinking?” Take, for example, the code to list all the threads in the current ThreadGroup. Rather than having the obvious method: i.e. one that returns a list (or array) of threads, the signature looks like this:
int enumerate(Thread[] list)

You pass an empty array to the method, which will be filled with
Thread
objects. The method then returns the number of threads it placed in the array. If the array is not long enough to accept all the threads, the overflow will be silently discarded.
To initialise the array, you must rely on
ThreadGroup#activeCount
, which only returns an approximation of the number of threads that
enumerate
might return.
If you’re looking to avoid memory leaks in a non-garbage-collected environment, then it makes perfect sense for an API to push responsibility for memory management back up its caller, and to gracefully handle whichever buffer-size it’s given to fill. When you’ve got pervasive GC, it just looks (and is) clumsy.
So the obvious answer to “What were they thinking?”, of course, is “They were thinking like C programmers”.
Which in turn leads one to suspect that this particular API has been around since before Java was called Java.
The Fishbowl: Charles Miller's Weblog
#另一方面,这个例子完美体现了GC语言的优势。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  api java c thread list up