Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4745629

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

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Won't Fix
    • Icon: P4 P4
    • None
    • 1.4.0
    • core-libs

      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)
      ======================================================================

            psoper Pete Soper (Inactive)
            nthompsosunw Nathanael Thompson (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: