What are the best practices around thread naming in Java? Are there any naming conventions to follow?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
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.
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'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:
Most significant part first
tends to sort badly so prefer Listener-http-01
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.