JDK-4745629 : (thread) Thread.setName does needless string allocations (don't use char[])
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 1.4.0
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: linux
  • CPU: x86
  • Submitted: 2002-09-11
  • Updated: 2014-11-10
  • Resolved: 2005-09-08
Related Reports
Relates :  
Description
Name: nt126004			Date: 09/11/2002


FULL PRODUCT VERSION :
java version "1.4.0_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_01-b03)
Java HotSpot(TM) Client VM (build 1.4.0_01-b03, mixed mode)


FULL OPERATING SYSTEM VERSION :
glibc-2.2.2-10
Linux twright 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686
unknown

A DESCRIPTION OF THE PROBLEM :
I'm using a Thread pool in my application.  I'd like to
set the thread name for each runnable that I schedule out of
my pool.  I'd also like thread dumps to show these names.

OptimizeIt reveals an oddity in "java.lang.Thread":
  a) Names are kept as "char[]"s instead of Strings
  b) Every call to "setName(String)" results in a clone of
     the passed String's character array.
  c) Every call to "getName()" results in yet another
     clone of the character array.
Lastly, "setName(String)" and "getName()" are final, so I
can't fix the problem by subclassing.

I see no need for this GC + performance overhead.


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
See the test below.

EXPECTED VERSUS ACTUAL BEHAVIOR :
Calls to "setName(String)" that don't change the name should
be no-ops.  Even if the name is being changed, it shouldn't
result in char[] / String allocations.  Thread should keep a
pointer to the String, not the char[].

Calls to "getName()" should be cheap.  Strings are immutable!

Serialization compatibilty is easy.  Hopefully JVMs + JNI
doesn't depend upon this char[], 'though it wouldn't
surprise me.  If you're concerned about holding onto
substrings, you could treat this as a special case.


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
Here's a test:

  Thread t = Thread.currentThread();
  while (true) {
     t.setName("foo");
  }

It's easy to make similar tests for "getName()".
---------- END SOURCE ----------

CUSTOMER WORKAROUND :
Suffer the GC overhead.  Or not rename the Threads and see
useless thread dumps.
(Review ID: 163857) 
======================================================================

Comments
EVALUATION There are dependencies on the name representation being a char array in the JVM and this RFE must be respectfully rejected.
08-09-2005

EVALUATION 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. ###@###.### 2002-09-11
11-09-2002