简体   繁体   中英

Run ExecutorService tasks continuously

I want to use method newWorkStealingPool() to get thread and run them continuously every 1 sec . Using the following sample code :

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());

        int initialDelay = 0;
        int period = 1;
        executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);

I can run task continuously but I want to use the method newWorkStealingPool() to get threads. Using the following code:

ScheduledExecutorService executor = (ScheduledExecutorService)Executors.newWorkStealingPool();

        Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());

        int initialDelay = 0;
        int period = 1;
        executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);

I got the error:

java.util.concurrent.ForkJoinPool cannot be cast to java.util.concurrent.ScheduledExecutorService

Using ExecutorService object it's possible to use newWorkStealingPool() but I don't know if is there any way to run ExecutorService object continuously like what object ScheduledExecutorService provides?

I think this can be achieved with creating ScheduledExecutorService and ForkJoinPool . ScheduledExecutorService will be used to submit tasks to ForkJoinPool at specified intervals. And ForkJoinPool will execute these tasks.

    ForkJoinPool executor = (ForkJoinPool) Executors.newWorkStealingPool();
    // this will be only used for submitting tasks, so one thread is enough
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());
    int initialDelay = 0;
    int period = 1;
    scheduledExecutor.scheduleAtFixedRate(()->executor.submit(task), initialDelay, period, TimeUnit.SECONDS);

The Executors.newWorkStealingPool() produces a ForkJoinPool . The ForkJoinPool class does not implement the ScheduledExecutorService interface so you cannot cast it to a ScheduledExecutorService .

Furthermore the ForkJoinPool and ScheduledExecutorService are fundamentally different thread pools. If you need to schedule a task to execute once every second stick with a ScheduledExecutorService , since it is suitable for your use case. ForkJoinPools are intended to use in cases where you have many small units of work divided among many threads, not for when you want to regularly execute something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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