java spring可运行任务超时

e1xvtsh3  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(358)

当数据库不可用时,队列会因为任务停止运行而增长。为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);
    }   
}
hkmswyz6

hkmswyz61#

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

相关问题