开发者

Should threads in Java be named for easier debugging?

What are the best practices around thread naming in Java? Are there any namin开发者_JAVA百科g conventions to follow?


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


Yes, naming threads certainly helps in identifying them, but with one caveat: make sure to give them unique names, because you can, if you choose to (or perhaps by accident), use the same name for multiple threads.

class Thread: Every thread has a name for identification purposes. More than one thread may have the same name.

Giving multiple threads the same name may make things worse and cause confusion instead of helping debugging.


I work on a system that has several Java processes running. Using log4j, I route all output to a single log file.

To get a general idea of where logging output is coming from, I use log4java's source thread output flag which prints the source thread name before the debug message.

So for me, it's essential to use good thread names.


I work mostly on stand-alone java applications, and sometimes the full thread dump is all we have to debug a problem. Thread names are vital there, too. They're one of those things that you don't really think about until you need them, and all your threads are named "Thread-145", etc.

That said, I haven't seen any particular naming conventions. Use something that you'll recognize later, where you aren't likely to re-use names. It might be worthwhile to make it clear from the name how many of that thread you expect to have active in the system, so you can tell if you have "thread leaks" later.


Yes, naming threads would be a good practice. If you have used Eclipse Debug and if your java application has threads implemented, you can clearly see the threads running in parallel with some random names, "Thread" followed by some number sequence. If you can give a meaningful name (again you may have to use a sequence, but thats entirely customizable and depends on you), it would be useful during Debug time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜