
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - Thread Pools
Thread Pools
A thread pool is a collection of pre-initialized threads. The general plan behind a thread pool is to form variety of threads at method startup and place them into a pool, wherever they sit and expect work. once a server receives a call for participation, it awakens a thread from this poolâif one is availableâand passes it the request for service. Once the thread completes its service, it returns to the pool and awaits a lot of work. If the pool contains no accessible thread, the server waits till one becomes free.
Why Use Thread Pools in Groovy?
It saves time as a result of there's no need to produce new thread.
It is utilized in Servlet and JSP wherever instrumentality creates a thread pool to method the request.
Creating Thread Pools in Groovy
Groovy uses a java.util.concurrent.Executors class provides couple of methods to create a thread pools.
Executors Class Methods
Following are few important and useful methods this class to create Thread Pools -
Sr.No. | Method & Description |
---|---|
1 |
public static ExecutorService newCachedThreadPool() Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. |
2 |
public static ExecutorService newFixedThreadPool(int nThreads) Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. |
3 |
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically. |
4 |
public static ExecutorService newWorkStealingPool() Creates a work-stealing thread pool using all available processors as its target parallelism level. |
Creating a Thread Pool Using newFixedThreadPool() Method
A fixed thread pool obtainted by calling the static newFixedThreadPool() method of Executors class.
Syntax
ExecutorService fixedPool = Executors.newFixedThreadPool(2);
Where,
Maximum 2 threads will be active to process tasks.
If more than 2 threads are submitted then they are held in a queue until threads become available.
A new thread is created to take its place if a thread terminates due to failure during execution shutdown on executor is not yet called.
Any thread exists till the pool is shutdown.
Example - Creating a Thread Pool Using newFixedThreadPool() Method
The following TestThread program shows usage of Executors newFixedThreadPool() method to create a thread pool of two threads. We're using a ThreadPoolExecutor object and initialized with newFixedThreadPool(2), a fix thread pool of size 2. Then we're printing various attributes of the threadpool. Then we're adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes.
Example.groovy
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; class Example { static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution println("Largest executions: " + pool.getLargestPoolSize()); println("Maximum allowed threads: " + pool.getMaximumPoolSize()); println("Current threads in pool: " + pool.getPoolSize()); println("Currently executing threads: " + pool.getActiveCount()); println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution println("Core threads: " + pool.getCorePoolSize()); println("Largest executions: " + pool.getLargestPoolSize()); println("Maximum allowed threads: " + pool.getMaximumPoolSize()); println("Current threads in pool: " + pool.getPoolSize()); println("Currently executing threads: " + pool.getActiveCount()); println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { void run() { try { Long duration = (long) (Math.random() * 5); println("Running Task! Thread Name: " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); println("Task Completed! Thread Name: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Output
The above program produces the following output −
Largest executions: 0 Maximum allowed threads: 2 Current threads in pool: 0 Currently executing threads: 0 Total number of threads(ever scheduled): 0 Core threads: 2 Largest executions: 2 Maximum allowed threads: 2 Current threads in pool: 2 Currently executing threads: 2 Total number of threads(ever scheduled): 4 Running Task! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1
Here although, we've submitted four threads but only two threads are executed as ThreadPool is fixed to accept only two threads.
Creating a Thread Pool Using newCachedThreadPool() Method
A cached thread pool obtainted by calling the static newCachedThreadPool() method of Executors class.
Syntax
ExecutorService executor = Executors.newCachedThreadPool();
Where,
newCachedThreadPool method creates an executor having an expandable thread pool.
Such an executor is suitable for applications that launch many short-lived tasks.
Example - Creating a Thread Pool Using newCachedThreadPool() Method
The following TestThread program shows usage of Executors newCachedThreadPool() method to create a expandable thread pool of threads. We're using a ThreadPoolExecutor object and initialized with newCachedThreadPool(). Then we're printing various attributes of the threadpool. Then we're adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes.
Example.groovy
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; class Example { static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution println("Largest executions: " + pool.getLargestPoolSize()); println("Maximum allowed threads: " + pool.getMaximumPoolSize()); println("Current threads in pool: " + pool.getPoolSize()); println("Currently executing threads: " + pool.getActiveCount()); println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution println("Core threads: " + pool.getCorePoolSize()); println("Largest executions: " + pool.getLargestPoolSize()); println("Maximum allowed threads: " + pool.getMaximumPoolSize()); println("Current threads in pool: " + pool.getPoolSize()); println("Currently executing threads: " + pool.getActiveCount()); println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); println("Running Task! Thread Name: " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); println("Task Completed! Thread Name: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Output
The above program produces the following output −
Largest executions: 0 Maximum allowed threads: 2147483647 Current threads in pool: 0 Currently executing threads: 0 Total number of threads(ever scheduled): 0 Core threads: 0 Largest executions: 4 Maximum allowed threads: 2147483647 Current threads in pool: 4 Currently executing threads: 4 Total number of threads(ever scheduled): 4 Running Task! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-4 Running Task! Thread Name: pool-1-thread-3 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-3 Task Completed! Thread Name: pool-1-thread-4 Task Completed! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1
Creating a Thread Pool Using newScheduledThreadPool() Method
A scheduled thread pool obtainted by calling the static newScheduledThreadPool() method of Executors class.
Syntax
ExecutorService executor = Executors.newScheduledThreadPool(1);
Example - Creating a Thread Pool Using newScheduledThreadPool() Method
The following TestThread program shows usage of Executors newScheduledThreadPool() method to create a thread pool of a thread. We're using a ScheduledExecutorService object as scheduler and initialized with newScheduledThreadPool(). We've created a ScheduledFuture object to schedule a task to execute every two seconds after an initial delay of two seconds. Using scheduler, we scheduled the task to run for ten seconds.
Example.groovy
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; class Example { static void main(String[] args) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { println("beep"); } } }
Output
The above program produces the following output −
beep beep beep beep beep