executor服务提交的未来获取回报为空 [英] Future get returns null from executor service submit

查看:114
本文介绍了executor服务提交的未来获取回报为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While performing an initial phase of Java to Groovy code migration I encountered a problem where the Groovy version returns null from the Future while Java returns the correct integer (123).

在J1.java和G1.groovy之间进行的唯一更改是类名和lambda到闭包的转换.

The only changes made between J1.java and G1.groovy are the class name and lambda to closure conversion.

//文件:J1.java

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

//文件:G1.groovy

//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

Java Result: 123

常规结果:null

这是预期的吗?如果是,为什么呢?我尝试了无数变体,所有变体都产生了相同的结果.使用Groovy无法产生相同的结果吗?

Is this expected and if so why? I have tried numerous variations all producing the same result. Is there something that I am missing to produce the same result using Groovy?

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

推荐答案

在Groovy中,闭包是RunnableCallable.

In Groovy, a closure is a Runnable and a Callable.

不幸的是,当您调用executor.submit { .. }时,运行时会选择调用executor.submit(Runnable),而不会返回任何值.

Unfortunaly, when you call executor.submit { .. }, the runtime choose to call executor.submit(Runnable) which doesn't return a value.

您应该将闭包显式转换为Callable:

You should explicitly cast your closure to a Callable :

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

这篇关于executor服务提交的未来获取回报为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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