Future将从执行程序服务提交返回null

时间:2016-02-19 16:45:49

标签: groovy

在执行Java到Groovy代码迁移的初始阶段时,我遇到了一个问题,即Groovy版本从Future返回null,而Java返回正确的整数(123)。

J1.java和G1.groovy之间唯一的变化是类名和lambda到闭包转换。

// file:J1.java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class J1 {
  public static void main (String... args) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool (1);
    Future<Integer> future = executor.submit (() -> 123);
    System.out.println ("Result: " + future.get ());
    executor.shutdown ();
  }
}

// file:G1.groovy

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class G1 {
  public static void main (String... args) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool (1);
    Future<Integer> future = executor.submit ({ -> 123 });
    System.out.println ("Result: " + future.get ());
    executor.shutdown ();
  }
}
  

Java结果:123

     

Groovy结果:null

这是预期的,如果是这样,为什么?我尝试了很多变化,都产生了相同的结果。是否有一些我缺少使用Groovy产生相同结果的东西?

Groovy: 2.4.5
Java: 1.8 64-bit
Platform: Windows 7 64-bit

1 个答案:

答案 0 :(得分:7)

在Groovy中,闭包是RunnableCallable

不幸的是,当你拨打executor.submit { .. }时,运行时会选择调用不会返回值的executor.submit(Runnable)

您应该将闭包明确地转换为Callable:

def executor = Executors.newFixedThreadPool(1)
def future = executor.submit ({ -> 123 } as Callable)
println "Result: ${future.get()}"
executor.shutdown()