Home > Tutorial > Java Thread Pool Sample Code

Java Thread Pool Sample Code

When you have a list of similar tasks to perform, creating a Java Thread Pool is a good option. Start off my creating a Runnable that takes care of the needed task. Create a thread pool with the number of threads you would like available to perform the tasks. Each task is submitted to the thread pool and when the available threads have completed all of the tasks, you can shutdown the thread pool.

I have discovered a few things about thread pools after using them a good bit. My first observation is that if you always have tasks to complete, it’s is probably best to keep the thread pool running. Second I have concluded that if you keep a thread pool running for the life of the parent application, starting it with a large number of threads may not be the best idea in terms of system resources.

The sample Java code below is pretty simple. I create a runnable with a purpose of sleeping for 10 seconds. I then create a thread pool with 3 threads and submit 6 tasks to the thread pool. Once the thread pool is done, it is shutdown and were done.

Java Thread Pool Source Code:

package com.jcd.java.tutorials;

import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class JavaThreadPool 
{
	
	public static void main(String[] args) 
    {
		int numberOfThreads = 3;
		int numberOfTasks = 6;
		final Collection<Future<?>> poolFutures = new LinkedList<Future<?>>();
		
		
		System.out.println("Start the ThreadPool");
		
		//Create a new thread pool with 3 threads
        ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);  
        
        Calendar.getInstance().getTime().toString();
        
        //Submit 6 tasks to the thread pool
        for (int i = 1; i <= numberOfTasks; i++) 
        {
            Runnable worker = new JavaWorkerThread(i);
            poolFutures.add(executor.submit(worker));
        }



		// Block here until all futures are done
		for (Future<?> future:poolFutures) 
		{
			
			try 
			{ 
				//This is a blocking call
				future.get();
			}
			catch(Exception ex) 
			{ 
				System.out.println("Exception:"+ex.toString()); 
			}
			
		}
		
		System.out.println("ThreadPool Completed");
		
		//All Tasks Have Completed, let's shutdown thread pool
		executor.shutdown();   
    }

}

class JavaWorkerThread implements Runnable 
{
  
    int taskNumber;
    
    public JavaWorkerThread(int taskNumber)
    {
        this.taskNumber = taskNumber;
    }

    @Override
    public void run() 
    {
        System.out.println(Thread.currentThread().getName()+" Started for Task#"+taskNumber+" at "+Calendar.getInstance().getTime().toString());
        
        //Dummy Timer task That Just Sleeps
        dummyTimerTask();
        
        System.out.println(Thread.currentThread().getName()+" Ended for Task#"+taskNumber+" at "+Calendar.getInstance().getTime().toString());
    }

    private void dummyTimerTask() 
    {
        try 
        {
        	System.out.println("Sleeping");
        	//Sleep for 10 seconds
            Thread.sleep(10000);
            
        } catch (Exception ex) 
        {
        	System.out.println("Exception:"+ex.toString());
        }
    }

}


You will notice from the log messages that tasks 4-6 don’t start until one of the threads from the thread pool completes the first 3 tasks. If you changed the thread pool threads to 6, you would see all 6 tasks running concurrently because the threads are available. You will need to fine tune the number of threads needed for your application.

Sample Java Thread Pool Output:

Start the ThreadPool
pool-1-thread-1 Started for Task#1 at Fri Jan 05 12:32:44 EST 2018
pool-1-thread-3 Started for Task#3 at Fri Jan 05 12:32:44 EST 2018
Sleeping
pool-1-thread-2 Started for Task#2 at Fri Jan 05 12:32:44 EST 2018
Sleeping
Sleeping
pool-1-thread-1 Ended for Task#1 at Fri Jan 05 12:32:54 EST 2018
pool-1-thread-2 Ended for Task#2 at Fri Jan 05 12:32:54 EST 2018
pool-1-thread-3 Ended for Task#3 at Fri Jan 05 12:32:54 EST 2018
pool-1-thread-2 Started for Task#4 at Fri Jan 05 12:32:54 EST 2018
Sleeping
pool-1-thread-1 Started for Task#5 at Fri Jan 05 12:32:54 EST 2018
Sleeping
pool-1-thread-3 Started for Task#6 at Fri Jan 05 12:32:54 EST 2018
Sleeping
pool-1-thread-2 Ended for Task#4 at Fri Jan 05 12:33:04 EST 2018
pool-1-thread-1 Ended for Task#5 at Fri Jan 05 12:33:04 EST 2018
pool-1-thread-3 Ended for Task#6 at Fri Jan 05 12:33:04 EST 2018
ThreadPool Completed



References:

Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot