发表时间:2009-01-07
最后修改:2009-01-07
今天看到InfoQ上的文章:Java 7 路线图更新:反响强烈 其中关于“闭包(closure)”的争论引起了俺的兴趣:
Ricky Clarkson认为没有闭包Java将灭亡
Martin Kneissl也认为Java 7中没有闭包是个坏消息
Dustin Marx在关于Java 7中最期待的特性的帖子中对闭包有一些矛盾的看法
Osvaldo Doederlein对新特性感到兴奋,不过仍然很期望闭包
对于如此万众期待的功能,为什么JDK开发团队最终决定不实现呢?而俺对Closure正好不太明白,就查了查Wikipedia关于closure的定义。从中发现了蛛丝马迹:
A language implementation cannot easily support full closures if its run-time memory model allocates all local variables on a linear stack. In such languages, a function's local variables are deallocated when the function returns. However, a closure requires that the free variables it references survive the enclosing function's execution. Therefore those variables must be allocated so that they persist until no longer needed. This explains why typically languages that natively support closures also use garbage collection. The alternative is for the language to accept that certain use cases will lead to undefined behaviour, as in the proposal for lambda expressions in C++.[4]
据我所知,Java语言对local variables的实现正是基于linear stack的(如果我错了,请大侠们指正)。也就是说,如果要基于现在的Java语言实现来加入closure功能是比较复杂且不优雅的,而且还有可能导致"undefined behaviour"。
换句话说,我猜想并不是JDK开发团队不想加入这个功能,而是他们在权衡得到的好处和付出的代价之后(主要是代价太大),最终不得不忍痛割爱了。
想得更深一步,现在以及未来,JVM已经不再仅限于支持Java语言的运行了。在这样的大背景下,类似closure这样的功能已经不应该再是一个可选择的特性。那么,对于JDK和JVM的实现,是否是时候来一次大的refactor了呢?