Java内部类和捕获对象

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

最佳答案

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

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

关于java - Java内部类和捕获对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37666581/

10-11 20:43