Java内部类和捕获对象

时间:2016-06-06 20:43:52

标签: java

以下代码摘自Google的Guava库(ThreadFactoryBuilder),用于返回使用用户定义的格式字符串命名线程的线程工厂。

 private static ThreadFactory build(ThreadFactoryBuilder builder) {
 ...
 final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
 return new ThreadFactory() {
    @Override public Thread newThread(Runnable runnable) {
      Thread thread = backingThreadFactory.newThread(runnable);
      if (nameFormat != null) {
        thread.setName(format(nameFormat, count.getAndIncrement()));
      }

问题是,上述代码与将AtomicLong计数器移动到ThreadFactory类本身相比是否有任何优势。即,以下代码:

 private static ThreadFactory build(ThreadFactoryBuilder builder) {
 ...
  return new ThreadFactory() {
    final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;

    @Override public Thread newThread(Runnable runnable) {
      Thread thread = backingThreadFactory.newThread(runnable);
      if (nameFormat != null) {
        thread.setName(format(nameFormat, count.getAndIncrement()));
      }

1 个答案:

答案 0 :(得分:2)

在实践中没有区别。第一个代码将被编译为与第二个代码基本相同的东西,除了它将生成一个合成构造函数以将AtomicLong引用存储在合成的本地字段中。

唯一的区别是首先实例化。除此之外没有区别。