我想在带有 @Test
注释的 TestNG 类中运行 CompletableFuture
。
下面是代码片段,recursionFuture
方法由 main()
方法递归调用以执行特定任务。
现在,如果我使用 main()
作为 public static void main(String[] args))
那么一切都会按预期工作。但是,当我将 main()
与 @Test
注释一起使用时,TestNG 会在中间停止执行,并且整个任务不会执行。
我应该怎么做才能让@Test
等待recursionFuture
完成所有任务?
我必须使用CompletableFuture
来执行异步任务,并且还需要使用@Test
。
如有任何帮助,我们将不胜感激。谢谢。
//public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException
@Test // --> this logic of recursion with threads is problematic with testNG
public static void main() throws FileNotFoundException, InterruptedException, ExecutionException
{
System.setOut(new PrintStream(new File("/Users/Pankaj/Desktop/Thread")));
Method[] method = ConcurrencyPoC_CompletableFuture.class.getMethods();
for(int i=0; i<method.length; i++)
{
if(method[i].getName().startsWith("task"))
{
TreeMap<Object, Object> m = new TreeMap<>();
m.put(method[i].getName(), method[i]);
m.put("status", new AtomicBoolean(true));
taskmap.put(method[i].getName(), m);
}
}
//submitting tasks
ExecutorService ex = Executors.newCachedThreadPool();
CompletableFuture<?> [] arrayFutures = new CompletableFuture[3];
recursionFuture(ex, arrayFutures);
}
public static String recursionFuture(ExecutorService ex, CompletableFuture<?> [] arrayFutures)
{
try
{
//check if any of submitted future is completed - to be used in case of array
for(CompletableFuture<?> future : arrayFutures)
{
future = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);
//storing future in a final variable for further calculation
final CompletableFuture<?> task = future;
CompletableFuture.anyOf(task).thenRunAsync(() ->
{
try {
//apply recursion only when future's output is not null, otherwise there will be hell lot of futures get created which
//don't do anything just eating up memory and executing the else block of executeTask() method.
// Latest change, as soon as any task is free, create a new array of 1 size to do the next task
if(task.get() != null)
recursionFuture(ex, new CompletableFuture[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
, ex);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return "ALl TASK COMPLETED";
}
最佳答案
TestNG @Test 注释和你的完整 future 之间没有对应关系。 问题出在你的tast.get()方法中。它应该阻塞正在运行的线程,直到所有可完成的 future 完成。
我在测试中使用 Completable Future,并且在使用 TestNG 时从未遇到过问题。
问题是你的 future 的完成之一,你返回到测试方法而不是等待所有的 future。您应该将所有 future 与 thenApplyAsync() 或 compose() 结合起来,因为您的 Future 是最终的,您只等待一个 future。另外,您不应该使用 CompletbleFuture.Any(),因为它会在第一个 future 完成时返回执行。
关于java - 如何在 testNG 类中使用 completableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876567/