1

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?

user2248702
  • 2,741
  • 7
  • 41
  • 69

2 Answers2

6

Although this is primarily opinion based, I'm using the following conventions in my code:

  • A Field or parameter that references an Executor or an ExecutorService is named executor or executorService. 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 or Callable to realize a long-running operation usually gets the suffix Task (like LoadTask, 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();
isnot2bad
  • 24,105
  • 2
  • 29
  • 50
0

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...

Community
  • 1
  • 1
Kyte
  • 834
  • 2
  • 12
  • 27
  • I think the question is about naming conventions for fields and classes, not about how to name the threads. – isnot2bad Jun 02 '14 at 16:04
  • hm. One possibility would be threadName_variableName or threadHash_variableName for a convention – Kyte Jun 02 '14 at 16:07