简体   繁体   English

来自Iterator的Java ExecutorService读取任务

[英]Java ExecutorService Read Tasks from Iterator

All, 所有,

I'm using a Java ExecutorService to perform tasks in parallel. 我正在使用Java ExecutorService并行执行任务。 Unfortunately, the list of tasks is now reaching the tens of millions. 不幸的是,任务列表现在达到了数千万。 This means that submitting the tasks to the executor service ahead of time is infeasible due to memory constraints. 这意味着由于内存限制,将任务提前提交给执行者服务是不可行的。

I am able to generate an iterator which dynamically creates the tasks as they are needed, but I'm not sure how best to apply this to the ExecutorService. 我能够生成一个迭代器,该迭代器可以根据需要动态创建任务,但是我不确定如何最好地将其应用于ExecutorService。

Should I create a task which pulls the next task from the iterator or is there some better way to do this? 我应该创建一个从迭代器中提取下一个任务的任务,还是有更好的方法呢?

A quick experiment produced this that kind of works. 一个快速的实验就产生了这种作品。 It certainly should demonstrate one way of doing it. 当然,它应该演示一种实现方法。

I create and run a ServiceFeeder which delivers Runnables to the service via the execute method. 我创建并运行一个ServiceFeeder ,它通过execute方法将Runnables传递给服务。

ExecutorService service = Executors.newFixedThreadPool(10);

class ServiceFeeder implements Runnable {
    final Iterator<Runnable> i;

    public ServiceFeeder(Iterator<Runnable> i) {
        this.i = i;
    }

    @Override
    public void run() {
        while (i.hasNext()) {
            service.execute(i.next());
        }
    }
}

public void test() throws Exception {
    System.out.println("Hello world!");
    // Demo Iterator<Runnable> - use yours.
    Iterator<Runnable> i = new Iterator<Runnable>() {
        volatile int n = 0;

        @Override
        public boolean hasNext() {
            return n < 100;
        }

        @Override
        public Runnable next() {
            return () -> System.out.println(n++);
        }
    };

    ServiceFeeder feeder = new ServiceFeeder(i);
    Thread feederThread = new Thread(feeder);
    feederThread.start();
    // Wait for the feeder to stop.
    feederThread.join();
    // Wait for the service to stop.
    service.shutdown();
}

This kind of works because it prints far more than I expected but that's not a problem as a demo IMHO. 这种工作方式是因为它的打印量远远超出了我的预期,但是作为演示恕我直言,这不是问题。

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

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