Reputation: 3427
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?
Upvotes: 1
Views: 1868
Reputation: 2560
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.
Upvotes: 0
Reputation: 7968
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);
Upvotes: 2