I have recently found myself using some ExecutorServices (SingleThreadScheduledExecutor and newFixedThreadPool) but I don't have any kind of good name for them.
Are there any kind of guidelines or conventions about naming these kinds of objects? I have seen names like "workerThread" used for SingleThreadScheduledExecutors, is this correct as they are not exactly threads?
Although this is primarily opinion based, I'm using the following conventions in my code:
- A Field or parameter that references an
Executor
or anExecutorService
is namedexecutor
orexecutorService
. The type of the executor should not be inferable by the name of the field as otherwise you cannot easily change the executor implementation afterwards. - A class that implements
Runnable
orCallable
to realize a long-running operation usually gets the suffixTask
(likeLoadTask
,ComputationTask
, ...). (As such an operation is not a thread, but is executed by a thread, and there is usually not a 1:1 mapping between threads and operations, it is wrong to call it thread).
This makes the code really readable and it does not make any assumption about thread usage, e.g.:
for (String fileName : fileNames) {
executor.execute(new LoadTask(fileName));
}
(This example might execute all load tasks in serial, in parallel or anything inbetween - according to the type of executor that's used).
One note about the word 'thread':
The word thread is not used anywhere except for the rare case where I have to either subclass from Thread
or create a field that references a (real) Thread
:
public class WorkerThread extends Thread { ... }
or:
Thread thread = Thread.currentThread();
This question is similar, it might be able to help you.
You can always build a string using a generic object name + PID + something else and hash the result. Chances of a hash collision are pretty low...
来源:https://stackoverflow.com/questions/23990818/executorservice-naming-conventions-java