首页 > 解决方案 > Java Spring Runnable 任务超时

问题描述

面对这样一个事实,当数据库不可用时,队列会因为任务停止运行而增长。为方法 run() 中执行的任务设置超时的最佳方法是什么?使用 ExecutorService 可能有一些好的方法吗?

@Service
public class AsyncWriter implements Writer, Runnable {
    
    private LinkedBlockingQueue<Entry> queue = new LinkedBlockingQueue<>();

    private volatile boolean terminate = false;

    private AtomicInteger completedCounter = new AtomicInteger();

    @PostConstruct
    private void runAsyncWriter() {
        Thread async = new Thread(this);
        async.setName("Writer Thread");
        async.setPriority(2);
        async.start();
    }

    @Override
    public void run() {
        while (!terminate) {
            try {
                Entry entry = queue.take();                
                    dao.save(entry);
                    completedCounter.incrementAndGet();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void write(Entry entry) {
        queue.add(entry);
    }   
}

标签: javaspringrunnable

解决方案


也许你可以试试 RxJava https://www.baeldung.com/rx-java 你可以在 RxJava 中设置你的 aync 函数 超时


推荐阅读