Java Executors.newScheduledThreadPool Example

By Arvind Rai, May 29, 2022
On this page we will learn using Executors.newScheduledThreadPool method.
The newScheduledThreadPool creates a thread pool that schedules the task or execute periodically. Find the newScheduledThreadPool method declarations.
a. With given number of threads.
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 
Creates a thread pool that can schedule tasks to run after a given delay, or to execute periodically.
The corePoolSize is the number of threads to keep in the pool, even if they are idle.
It returns the newly created scheduled thread pool.
if corePoolSize < 0, it throws IllegalArgumentException.

b. With given number of threads and thread factory.
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) 
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
The corePoolSize is the number of threads to keep in the pool, even if they are idle.
The threadFactory is the factory to use when the executor creates a new thread.
It returns the newly created scheduled thread pool.
if corePoolSize < 0, it throws IllegalArgumentException.

ScheduledExecutorService

The ScheduledExecutorService is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically. Find its methods to schedule the task.
a.
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) 
Submits a one-shot task that becomes enabled after the given delay.
b.
ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) 
Submits a value-returning one-shot task that becomes enabled after the given delay.
c.
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 
Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period.
d.
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 
Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Example-1

Find the newScheduledThreadPool example with Runnable.
ExecutorDemo1.java
package com.concretepage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ExecutorDemo1 {
  public static void main(final String... args) throws InterruptedException {
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
	
	Runnable task = () -> System.out.println("Hello World!");
	ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(task, 3 , 2, TimeUnit.SECONDS);
	
	Runnable cancelTask = () -> taskHandle.cancel(false);
	scheduler.schedule(cancelTask, 10, TimeUnit.SECONDS);
	
	scheduler.awaitTermination(12, TimeUnit.SECONDS);
	scheduler.shutdownNow();	
  }
} 
Output
Hello World!
Hello World!
Hello World!
Hello World! 

Example-2

Find the newScheduledThreadPool example with Callable.
ExecutorDemo2.java
package com.concretepage;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ExecutorDemo2 {
  public static void main(final String... args) throws InterruptedException, ExecutionException {
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	
	Callable<Integer> task1 = () -> 5 * 20;
	Callable<Boolean> task2 = () -> 10 > 5;
	
	ScheduledFuture<?> task1Handle1 = scheduler.schedule(task1, 2, TimeUnit.SECONDS);
	ScheduledFuture<?> task1Handle2 = scheduler.schedule(task2, 3, TimeUnit.SECONDS);
	
	System.out.println(task1Handle1.get());
	System.out.println(task1Handle2.get());
	
	scheduler.awaitTermination(5, TimeUnit.SECONDS);
	scheduler.shutdownNow();
  }
} 
Output
100
true 

Example-3

Find the newScheduledThreadPool example with given ThreadFactory.
ExecutorDemo3.java
package com.concretepage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class ExecutorDemo3 {
  public static void main(final String... args) throws InterruptedException {
	MaxPriorityThreadFactory threadFactory = new MaxPriorityThreadFactory();   
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2, threadFactory);
	
	Runnable task = () -> System.out.println("Hello World!");
	ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(task, 3 , 2, TimeUnit.SECONDS);
	
	Runnable cancelTask = () -> taskHandle.cancel(false);
	scheduler.schedule(cancelTask, 10, TimeUnit.SECONDS);
	
	scheduler.awaitTermination(12, TimeUnit.SECONDS);
	scheduler.shutdownNow();	
  }
}
class MaxPriorityThreadFactory implements ThreadFactory {
  @Override
  public Thread newThread(Runnable r) {
	Thread t = new Thread(r);
	t.setPriority(Thread.MAX_PRIORITY);
	return t;
  }
} 
Output
Hello World!
Hello World!
Hello World!
Hello World! 

Reference

Class Executors
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us