When i was dealing with threads concept in Java, i have seen Thread.java source file. I noticed when setName()
method assigns string to a character array called "name[]"
. Java has a feature of String data type, then why they are using character array.
In source file it is initialised like,
private char name[]; // why not "private String name;"
In setName()
method,
public final void setName(String name) {
checkAccess();
this.name = name.toCharArray();
}
Please help me. Thanks in advance.
Example of naming a thread : Without Using setName() MethodOne can also set the name of a thread at the time of the creation of a thread, without using the setName() method. Observe the following code. // the superclass, which is Thread class.
A: When more than one thread try to access same resource without synchronization causes race condition. So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.
Explanation: wait() method is used to tell the calling thread to give up a monitor and go to sleep until some other thread enters the same monitor.
A thread can be given a name in its constructor. In addition, it can be specified via a Thread object's setName() method. In addition, it should be noted that a thread is given an identification number that can be retrieved via the thread's getId() method.
This name is accessed from native code, so it is easier to handle char arrays than mangle with Java types. The core-lib-devs
mailing list discussed this question a while ago, here's a link to one mail from the thread. The original question stated that "a fair amount of time goes to that Thread.setName call which I believe a significant portion is to do new char allocation and copy char array etc". Quoting bits of the answer:
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With