Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should threads in Java be named for easier debugging?

What are the best practices around thread naming in Java? Are there any naming conventions to follow?

like image 563
parkr Avatar asked Jul 01 '10 12:07

parkr


People also ask

Why naming a thread is useful?

Naming ThreadThe Thread class provides methods to change and get the name of a thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName() method.

Which method is used for to call the thread?

The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

Is thread name unique in Java?

The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime.


1 Answers

I'd say that a general Best Practice is "choose good names", this applies to variables, methods, computers, possibly even children (just ask my son Gerund Extravagaza Smith).

So yes, choose meaningful names for your threads if possible.

Suppose we asked for a naming convention for files or computers. Would you expect there to be a generally applicable answer? I think that you need to generate a convention of your own that makes sense with the kind of threads your create.

I would follow these general principles:

  • Short, lets avoid reallyLongNamesWithManyProbablyIrreleventClauses-Thread-01
  • Meaningful, but accept that you may have a pool of threads job-01, job-02
  • Most significant part first

    01-http-Listener 
    01-rmi-Listener
    02-http-Listener
    

    tends to sort badly so prefer Listener-http-01

like image 122
djna Avatar answered Sep 28 '22 19:09

djna