java - 为什么 Thread 类中的 setName 分配给字符数组?为什么不是字符串?

标签 java

当我处理 Java 中的线程概念时,我看到了 Thread.java 源文件。我注意到 setName() 方法将字符串分配给名为 "name[]" 的字符数组。 Java 有一个 String 数据类型的特性,那么为什么他们使用字符数组。

在源文件中,它被初始化为,

private char name[]; // why not "private String name;"

setName()方法中,

public final void setName(String name) {
    checkAccess();
    this.name = name.toCharArray();
    }

请帮帮我。提前致谢。

最佳答案

此名称可从 native 代码访问,因此处理 char 数组比处理 Java 类型更容易。 core-lib-devs 邮件列表不久前讨论了这个问题,这里是来自线程的一封邮件的 link。最初的问题是 “相当多的时间用于 Thread.setName 调用,我认为其中很大一部分是进行新的字符分配和复制字符数组等”。引用部分答案:

There was an RFE for this way back in late 2002:

4745629 (thread) Thread.setName does needless string allocations (don't use char[])

The initial eval in 2002 stated:

"I can't imagine that this seriously impacts the performance of any real program. Furthermore, changing the fields in Thread is problematic due to the close relationship of this class with the VM. That said, it might be worth addressing this in the context of some Thread code-cleanup."

Then in 2005 it was closed as "will not fix":

"There are dependencies on the name representation being a char array in the JVM and this RFE must be respectfully rejected."

关于java - 为什么 Thread 类中的 setName 分配给字符数组?为什么不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412408/

相关文章:

java - 使用java从具有唯一标识符的字符串中获取子字符串

java - Veracode CWE 384 session 固定

java - 能够选择同一组中的两个单选按钮

java - NaN 的总和 : How is the underlying bit pattern calculated?

java - 如何处理很长的XPATH?有什么替代方案吗?

Java 选择布局问题

java - maven安装lib文件夹的快速方法

java - 可选.ifPresent(如果不存在怎么办)

java - “找不到符号”或“无法解析符号”错误是什么意思?

java - 无法将 java spring boot 中的文件上传到 tomcat 托管服务器,始终显示对 fedora 中给定文件上传路径的访问权限