When will Runnable.toString () be able to return a duplicate string?

When will this.toString () possibly return a duplicate string?

public static void main(java.lang.String s[]) {
    for(int i=0;i<155000;i++) {
        new Thread(new Runnable() {
            public void run() {
                System.out.println(this.toString());
            }
        }).start();
    }
}

      

+3


source to share


3 answers


Thomas's answer is correct in that the Object

default method toString()

will be called, which creates different String

for different objects.

One note here. Object.toString()

returns:

return getClass().getName() + "@" + Integer.toHexString(hashCode());

      

It includes Object.hashCode()

. The javadoc hashCode () states:



... the hashCode method defined by the class Object

returns different integers for individual objects ...

The key is that it hashCode()

will be different for individual objects. Since your code does not store the generated Runnable

s, once Thread

completed they will be garbage collected. After the object is removed from memory, another symbol Object

may take its place in memory, and it is possible that the new one Runnable

will provide the same hash code that was returned by the previous one Runnable

, which is now terminated .

So it is theoretically possible that you will see the same ones String

printed indeterministically (although the chances are very slim).

+6


source


Since toString()

by default it just returns the class and object id, there should never be duplicates in your case. You are basically creating 155k different anonymous instances Runnable

(s Thread

).



+4


source


From the doc: A method toString()

for a class Object

returns a string consisting of the name of the class whose object is the object instance, the at-sign `@ 'character, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

      

The method used toString()

has a class Object

. And as you can see, it includes hashCode, so it will never print duplicate values, assuming all instances of your previous one Runnable

are still IN memory.

+2


source







All Articles