🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The ThreadPoolExecutor class in Java provides the getThreadFactory() method to retrieve the current ThreadFactory used by the executor to create new threads. This guide will cover the usage of the getThreadFactory() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.
Introduction
The getThreadFactory() method is used to retrieve the ThreadFactory that is used by the ThreadPoolExecutor to create new threads. A ThreadFactory is an interface that allows you to customize the creation of new threads, such as setting thread names, priorities, and daemon status.
getThreadFactory Method Syntax
The syntax for the getThreadFactory method is as follows:
public ThreadFactory getThreadFactory()
- The method does not take any parameters.
- The method returns a
ThreadFactoryobject representing the current thread factory used by the executor.
Examples
Example 1: Basic Usage of getThreadFactory()
In this example, we create a ThreadPoolExecutor, retrieve its default thread factory using the getThreadFactory() method, and print information about the created threads.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
public class GetThreadFactoryExample {
public static void main(String[] args) {
// Create a ThreadPoolExecutor with 2 threads
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
// Get the default thread factory
ThreadFactory threadFactory = executor.getThreadFactory();
// Submit tasks to the executor
for (int i = 0; i < 3; i++) {
final int taskNumber = i + 1;
executor.submit(() -> {
Thread thread = Thread.currentThread();
System.out.println("Executing task " + taskNumber + " by " + thread.getName());
try {
Thread.sleep(2000); // Simulate task execution
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskNumber + " completed by " + thread.getName());
});
}
// Shutdown the executor
executor.shutdown();
}
}
Output:
Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Executing task 3 by pool-1-thread-1
Task 1 completed by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Task 3 completed by pool-1-thread-1
Example 2: Using a Custom Thread Factory
In this example, we create a ThreadPoolExecutor with a custom thread factory to set custom thread names and then use the getThreadFactory() method to retrieve and print the custom thread factory.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
public class CustomThreadFactoryExample {
public static void main(String[] args) {
// Create a custom thread factory
ThreadFactory customThreadFactory = new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread thread = defaultFactory.newThread(r);
thread.setName("CustomThread-" + threadNumber.getAndIncrement());
return thread;
}
};
// Create a ThreadPoolExecutor with the custom thread factory
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2, customThreadFactory);
// Get the custom thread factory
ThreadFactory threadFactory = executor.getThreadFactory();
// Submit tasks to the executor
for (int i = 0; i < 3; i++) {
final int taskNumber = i + 1;
executor.submit(() -> {
Thread thread = Thread.currentThread();
System.out.println("Executing task " + taskNumber + " by " + thread.getName());
try {
Thread.sleep(2000); // Simulate task execution
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskNumber + " completed by " + thread.getName());
});
}
// Print the custom thread factory
System.out.println("Thread factory: " + threadFactory);
// Shutdown the executor
executor.shutdown();
}
}
Output:
Executing task 1 by CustomThread-1
Executing task 2 by CustomThread-2
Executing task 3 by CustomThread-1
Thread factory: CustomThreadFactoryExample$1@<hashcode>
Task 1 completed by CustomThread-1
Task 2 completed by CustomThread-2
Task 3 completed by CustomThread-1
Example 3: Customizing Thread Properties
In this example, we create a custom thread factory to set specific properties for the threads, such as setting them as daemon threads.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
public class CustomThreadPropertiesExample {
public static void main(String[] args) {
// Create a custom thread factory
ThreadFactory customThreadFactory = new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread thread = defaultFactory.newThread(r);
thread.setName("DaemonThread-" + threadNumber.getAndIncrement());
thread.setDaemon(true);
return thread;
}
};
// Create a ThreadPoolExecutor with the custom thread factory
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2, customThreadFactory);
// Submit tasks to the executor
for (int i = 0; i < 3; i++) {
final int taskNumber = i + 1;
executor.submit(() -> {
Thread thread = Thread.currentThread();
System.out.println("Executing task " + taskNumber + " by " + thread.getName() + " (daemon: " + thread.isDaemon() + ")");
try {
Thread.sleep(2000); // Simulate task execution
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskNumber + " completed by " + thread.getName());
});
}
// Shutdown the executor
executor.shutdown();
}
}
Output:
Executing task 1 by DaemonThread-1 (daemon: true)
Executing task 2 by DaemonThread-2 (daemon: true)
Executing task 3 by DaemonThread-1 (daemon: true)
Task 1 completed by DaemonThread-1
Task 2 completed by DaemonThread-2
Task 3 completed by DaemonThread-1
Conclusion
The ThreadPoolExecutor.getThreadFactory() method in Java is used for retrieving the current thread factory used by the executor to create new threads. By using custom thread factories, you can customize the properties of threads created by the executor, such as setting custom thread names, priorities, and daemon status.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment