Get unique thread id in Java 1.4

In Java 1.4, is there a better way to get the thread id than using Thread.getName()?

I mean that getName()in unit tests it returns something like "Thread-1", but in WebLogic 10 I get "[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml".

+5
source share
4 answers

Thread.getId (theoretically, it is possible to overflow , but this is determined not so and in practice will not be).

1.5 is going through an end-of-life period, but if you are using old 1.4 dust decks, you can implement your own with ThreadLocal. (Note that you are not following the Java SE 6 API documents too closely!)

+8
source

Why do you need this? Because depending on your answer, there are several approaches.

First make sure that the stream name is not unique. The hashcode id is not.

If you really want to associate a unique identifier with a stream, you will need to do it yourself. Perhaps using IdentityHashMap. However, this will result in a strong link that you do not want to host in the production application.

: TofuBeer , , , , , .

+3

"Thread.getId() " SO Thread.java:

/* For generating thread ID */
private static long threadSeqNumber;

/* Set thread ID */
tid = nextThreadID();

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

, java1.4.
, , .
, , , , , :

  • still linked to the internal 1.4 JVM managed naming policy ("Thread-1", "Thread-2", ...)
+3
source

You can use getID if you are using JDK 1.5 or higher.

In this case, do you need a consistent value for each run of unit tests or is the unique value just good enough?

+2
source

All Articles