ExecutorService命名约定Java [英] ExecutorService naming conventions Java

查看:75
本文介绍了ExecutorService命名约定Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现自己使用了一些ExecutorServices(SingleThreadScheduledExecutor和newFixedThreadPool),但是我对它们没有任何好名声.

I have recently found myself using some ExecutorServices (SingleThreadScheduledExecutor and newFixedThreadPool) but I don't have any kind of good name for them.

是否存在有关命名此类对象的准则或约定?我见过用于SingleThreadScheduledExecutors之类的名称,例如"workerThread",这是正确的,因为它们不是完全线程吗?

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:

  • 引用ExecutorExecutorService的字段或参数被命名为executorexecutorService.不能通过字段名称来推断执行程序的类型,否则您以后将无法轻易更改执行程序的实现.
  • 实现RunnableCallable来实现长时间运行的操作的类通常获得后缀Task(如LoadTaskComputationTask,...). (由于这样的操作不是不是线程,而是是由执行的,并且线程与操作之间通常没有1:1的映射,所以这样做是错误的称为 thread ).
  • 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).

关于线程"一词的注释:

除了在极少数情况下我必须从Thread继承子类或创建引用(真实)Thread的字段之外,在任何地方都没有使用 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 { ... }

或:

Thread thread = Thread.currentThread();

这篇关于ExecutorService命名约定Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆