Home > Tutorial > Java Custom Thread Pool Name Sample Code

Java Custom Thread Pool Name Sample Code

When you create a Java thread pool your not stuck with the default naming of pool-1-thread-1. When it comes time to diagnose a problem with your Java code, it is much better to be able to give the thread pool a more meaningful name based on your Java application, especially if you have more than one Java thread pool running.

The sample Java method below implements the ThreadFactory interface and overrides the newThread() method to change the naming of the thread pool. You can change it to whatever makes sense for your Java program.

Java Custom Thread Pool Name Source Code:

package com.jcd.java.tutorials;

import java.util.concurrent.ThreadFactory;


public class JavaCustomThreadFactory implements ThreadFactory
{
	
	private int counter = 0;
	private String prefix = "";

	public JavaCustomThreadFactory(String prefix) 
	{
		this.prefix = prefix;
	}

	@Override
	public Thread newThread(Runnable r) 
	{
		return new Thread(r, prefix + "-" + counter++);
	}
}


Importing the above sample java method into the Java Thread Pool Tutorial previously, you will notice the naming of the Java thread pool has changed.Try it out!

Sample Java Custom Thread Pool Output:

Start the ThreadPool
custom-thread-pool-2 Started for Task#3 at Fri Jan 05 15:07:28 EST 2018
custom-thread-pool-0 Started for Task#1 at Fri Jan 05 15:07:28 EST 2018
Sleeping
custom-thread-pool-1 Started for Task#2 at Fri Jan 05 15:07:28 EST 2018
Sleeping
Sleeping
custom-thread-pool-0 Ended for Task#1 at Fri Jan 05 15:07:38 EST 2018
custom-thread-pool-2 Ended for Task#3 at Fri Jan 05 15:07:38 EST 2018
custom-thread-pool-1 Ended for Task#2 at Fri Jan 05 15:07:38 EST 2018
custom-thread-pool-2 Started for Task#4 at Fri Jan 05 15:07:38 EST 2018
Sleeping
custom-thread-pool-0 Started for Task#5 at Fri Jan 05 15:07:38 EST 2018
Sleeping
custom-thread-pool-1 Started for Task#6 at Fri Jan 05 15:07:38 EST 2018
Sleeping
custom-thread-pool-2 Ended for Task#4 at Fri Jan 05 15:07:48 EST 2018
custom-thread-pool-1 Ended for Task#6 at Fri Jan 05 15:07:48 EST 2018
custom-thread-pool-0 Ended for Task#5 at Fri Jan 05 15:07:48 EST 2018
ThreadPool Completed



References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot