java - 关键字 final 对 JVM 有什么影响吗?

标签 java multithreading performance jvm

<分区>

现在,我最近遇到了一条建议,建议您应尽可能广泛地使用关键字 final。这很好,可以防止程序员开枪打自己的腿——也就是说,重新分配不应重新分配的变量。

但是,它还有其他目的吗?也就是说,JVM 能否使用有关最终变量的信息以某种方式优化字节码,使其运行得更快(构建更好的流水线或在多线程环境中使用它)?或者只是一种语法糖,可以最大限度地减少代码开发过程中出错的可能性?

最佳答案

IBM states:

Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.

关于java - 关键字 final 对 JVM 有什么影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506350/

相关文章:

Java:将数组发送到 PL-SQL 函数

C# Thread UI 被阻塞 | WebRequest.Create 的可能原因?

java - 处理文件下载等线程任务中的错误

mysql - Mysql中简单查询速度慢

java - FindBugs 警告 : Inefficient use of keySet iterator instead of entrySet iterator

c - 计算某个IP范围和时间范围内的访问次数的有效方法

java - 单核处理器还能抛出ConcurrentModificationException吗?

java - 使用 Hibernate,有没有办法避免在 HQL/SQL/Criteria 条件中使用字符串作为列名?

java - 如何将两个场景合并为一个场景?

multithreading - CopyOnWriteArrayList不能按预期工作