简体   繁体   English

如何在后台执行服务并检查其状态

[英]How to execute a service on backgroud and check its status

I'm executing a heavy calculation on the server.我正在服务器上执行繁重的计算。 The execution is launched from the front and the front is checking the status of the execution each 3 sec.执行从前端启动,前端每 3 秒检查一次执行状态。

So I wrote a service like the following :所以我写了一个如下的服务:

public class SomeService {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Future<?> noop = CompletableFuture.completedFuture(null);
    private final AtomicReference<Future<?>> currentExecution = new AtomicReference<>(noop);


    public void execute() {

        Future<?> execution = executor.submit(() -> {
            // do some heavy calculation here
            // ...
            // ...

            currentExecution.set(noop);
        });

        currentExecution.set(execution);
    }

    public boolean isRunning() {
        return !currentExecution.get().isDone();
    }
}

isRunning method is exposed as an api to the front. isRunning方法作为 api 暴露在前面。

I'm wondering if there's bugs here?我想知道这里是否有错误?

Maybe there's another elegant solution for this requirement?也许这个要求还有另一个优雅的解决方案?

A simple flag, set when the computation completes, would suffice, as long as it's volatile .一个简单的标志,在计算完成时设置,就足够了,只要它是volatile

private volatile boolean done;

public void execute() {
    executor.submit(() -> {
        /* Do some heavy calculation here. */
        done = true;
    });
}

public boolean isDone() {
    return done;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM