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

本文探讨了Java中ThreadGroup API的一个具体实现方式,并对其设计思路进行了幽默化的批评。指出其设计更像C语言风格而非现代垃圾回收语言的常规做法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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语言的优势。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值