ExecutorService naming conventions Java

∥☆過路亽.° 提交于 2019-12-08 04:21:52

问题


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?


回答1:


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();



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!